2015-01-08 3 views
0

Я добавил намерение электронной почты к приложению Android с кодом, чтобы добавить локальный файл в качестве привязки.Добавление приложения с использованием намерения электронной почты Android

Но когда кнопку я нажимаю «по электронной почте данные», чтобы открыть намерение я получить приложение, аварии и войти кошка показывает вывод следующий, http://hastebin.com/idejavunam.avrasm, ошибка исключения нулевого указателя находится на этой линии:

case R.id.emailBtn:

поэтому я думал, что это проблема с файлом uri, но не могу понять, почему, поскольку файл существует в файловой системе устройства.

Кто-нибудь знает, как я могу отладить эту проблему? Возможно, я неправильно передал путь к файлу?

Это тот процесс, который я выполняю для реализации решения.

код из метода, который создает CSV файл:

 String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); 
     String fileName = "AnalysisData.csv"; 
     //this filePath is used in email code and converted to Uri. 
     filePath = baseDir + File.separator + fileName; 
     File f = new File(filePath); 

И это код, в котором называется электронная умысел, с путем к файлу, преобразованный в Uri для крепления prposes:

case R.id.emailBtn: { 
      Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show(); 
      Uri.fromFile(new File(filePath)); 
      Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
         "mailto","[email protected]", null)); 
      emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT"); 
      emailIntent.putExtra(Intent.EXTRA_STREAM, filePath); 
      startActivity(Intent.createChooser(emailIntent, "Send email...")); 


      break; 

ответ

1

Я изменил часть проверки части, если она работает сейчас.

case R.id.emailBtn: { 
      Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show(); 
      Uri uri = Uri.fromFile(new File(filePath)); 
      Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
         "mailto","[email protected]", null)); 
      emailIntent.setType("*/*"); 
      emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT"); 
      emailIntent.putExtra(Intent.EXTRA_STREAM, uri); 
      startActivity(Intent.createChooser(emailIntent, "Send email...")); 


      break; 

UPDATE

Кроме того, посмотрев на LogCat я обнаружил, что ваш путь_к_файлу является нулевым. любезно правильно, что

EDIT

Я изменил ваш метод OnClick просто заменить скажите мне, если он работает для вас

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); 
    String fileName = "AnalysisData.csv"; 
    filePath = baseDir + File.separator + fileName; 
    File f = new File(filePath); 
    switch (v.getId()) { 
     case R.id.exportBtn: { 
      Toast.makeText(this, "select clicked", Toast.LENGTH_SHORT).show(); 
      //write sample data to csv file using open csv lib. 
      date = new Date(); 



      CSVWriter writer = null; 

      // File exist 
      if(f.exists() && !f.isDirectory()){ 
       FileWriter mFileWriter = null; 
       try { 
        mFileWriter = new FileWriter(filePath , true); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       writer = new CSVWriter(mFileWriter); 
      } 
      else { 
       try { 
        writer = new CSVWriter(new FileWriter(filePath)); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      String data [] = new String[] {"Record Number","Ship Name","Scientist Name","Scientist Email","Sample Volume","Sample Colour","Sample Material","Latitude","Longitude","Date","\r\n"}; 
      writer.writeNext(data); 

     /* 
     //retrieve record cntr from prefs 
     SharedPreferences settings = getSharedPreferences("RECORD_PREF", 0); 
     recordCntr = settings.getInt("RECORD_COUNT", 0); //0 is the default value 
     */ 

      //increment record count 
      recordCntr++; 

     /* 
     //save record cntr from prefs 
     settings = getSharedPreferences("RECORD_PREF", 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putInt("RECORD_COUNT",recordCntr); 
     editor.commit(); 
     */ 
      data = new String[]{Integer.toString(recordCntr),shipName,analystName,analystEmail,sampleVolume, 
        sampleColour,sampleMaterial,latitudeValue.toString(),longitudeValue.toString(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date),"\r\n"}; 

      writer.writeNext(data); 
      try { 
       writer.close(); 
       Toast.makeText(this, "Data exported succesfully!", Toast.LENGTH_SHORT).show(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       Toast.makeText(this, "Error exporting data!", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
     } 

     case R.id.emailBtn: { 

      Toast.makeText(this, "email clicked", Toast.LENGTH_SHORT).show(); 
      if (f.exists() && !f.isDirectory()) { 
       Uri uri = Uri.fromFile(f); 
       Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
         "mailto","[email protected]", null)); 
       emailIntent.setType("*/*"); 
       emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT"); 
       emailIntent.putExtra(Intent.EXTRA_STREAM, uri); 
       startActivity(Intent.createChooser(emailIntent, "Send email...")); 
      } 


      break; 
     } 
    } 

} 
+0

любезно найти обновление, чтобы найти ошибку, а также изменить код, чтобы соответствовать предоставленный код. –

+0

@BrianJ, так как трудно получить поток из вышеуказанных фрагментов кода, вы можете поделиться своим полным файлом java? –

+1

Я обновил свой ответ, проверив обновление –

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