2015-05-30 20 views
8

Vorrei aprire un file PDF quando l'utente fa clic su un pulsante. Attualmente, sto usando questo codice per ottenere questo:Impossibile aprire il file PDF nell'app esterna

Uri path = Uri.fromFile(new File("file:///android_asset/regola11_1.pdf")); 
      Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
      pdfIntent.setDataAndType(path, "application/pdf"); 
      pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(pdfIntent); 

ma non funziona.

quando seleziono di utilizzare Adobe Acrobat, ricevo un messaggio, visualizzato come un brindisi, che dice

"This file could not be accessed Check the location or the network and try again." 

Quando provo con azionamento PDF Viewer, ottengo

"Cannot display PDF (regola11_1.pdf cannot be opened)" 

Il PDF il file è memorizzato in

app > build > intermediates > assets 

Dove è il problema?

EDIT

Ora sto utilizzando il seguente codice:

File file = new File("\"file:///android_asset/regola11_1.pdf"); 
      Uri path = Uri.fromFile(file); 
      Intent intent = new Intent(Intent.ACTION_VIEW); 
      intent.setDataAndType(path, "application/pdf"); 
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      try { 
       context.startActivity(intent); 
      } 
      catch (ActivityNotFoundException e) { 
       Toast.makeText(context, "No application available to view PDF", Toast.LENGTH_LONG).show(); 
      } 

Ma quando provo ad aprire il PDF cliccando sul pulsante, l'applicazione si blocca.

Questo è il log ottengo:

05-31 10:05:25.132 24474-24474/? E/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: com.andrey.andreyvedis.iamaref, PID: 24474 
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference 
     at com.andrey.andreyvedis.iamaref.FragmentR11.onClick(FragmentR11.java:147) 
     at android.view.View.performClick(View.java:4781) 
     at android.view.View$PerformClick.run(View.java:19873) 
     at android.os.Handler.handleCallback(Handler.java:739) 
     at android.os.Handler.dispatchMessage(Handler.java:95) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5293) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 

Questa è la mia classe:

public class FragmentR11 extends Fragment implements View.OnClickListener{ 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private static final String ARG_PARAM1 = "param1"; 
private static final String ARG_PARAM2 = "param2"; 
Context context; 



// TODO: Rename and change types of parameters 
private String mParam1; 
private String mParam2; 


/** 
* Use this factory method to create a new instance of 
* this fragment using the provided parameters. 
* 
* @param param1 Parameter 1. 
* @param param2 Parameter 2. 
* @return A new instance of fragment FragmentR11. 
*/ 
// TODO: Rename and change types and number of parameters 
public static FragmentR11 newInstance(String param1, String param2) { 
    FragmentR11 fragment = new FragmentR11(); 
    Bundle args = new Bundle(); 
    args.putString(ARG_PARAM1, param1); 
    args.putString(ARG_PARAM2, param2); 
    fragment.setArguments(args); 
    return fragment; 
} 

public FragmentR11() { 
    // Required empty public constructor 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (getArguments() != null) { 
     mParam1 = getArguments().getString(ARG_PARAM1); 
     mParam2 = getArguments().getString(ARG_PARAM2); 
    } 



} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    return inflater.inflate(R.layout.fragment_r11, container, false); 


} 

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 

    getActivity().findViewById(R.id.bD1).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD2).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD3).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD4).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD5).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD6).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD7).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD8).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD9).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD10).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD11).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD12).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD13).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD14).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD15).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD16).setOnClickListener(this); 
    getActivity().findViewById(R.id.bD17).setOnClickListener(this); 


} 

/**private void openPDF(final String pathToPDF) { 
    File file = new File(pathToPDF); 
    Uri path = Uri.fromFile(file); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.setDataAndType(path, "application/pdf"); 
    try { 
     startActivity(intent); 
    } catch (ActivityNotFoundException e) { 
     Toast.makeText(getActivity(), "Devi installare un'app per aprire PDF, come Adobe Acrobat Reader ", Toast.LENGTH_SHORT).show(); 
    } 
}*/ 


@Override 
public void onClick(View v) { 



    switch(v.getId()){ 

     case R.id.bD1: { 

      /**Uri path = Uri.fromFile(new File("regola11_1.pdf")); 
      Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
      pdfIntent.setDataAndType(path, "application/pdf"); 
      pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(pdfIntent); 
      Toast.makeText(getActivity(), "Hai cliccato Regola 1 in Reg11 ", Toast.LENGTH_SHORT).show();*/ 

      File file = new File("\"file:///android_asset/regola11_1.pdf"); 
      Uri path = Uri.fromFile(file); 
      Intent intent = new Intent(Intent.ACTION_VIEW); 
      intent.setDataAndType(path, "application/pdf"); 
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      try { 
       context.startActivity(intent); 
      } 
      catch (ActivityNotFoundException e) { 
       Toast.makeText(context, "No application available to view PDF", Toast.LENGTH_LONG).show(); 
      } 
      break; 
     } 

     case R.id.bD2: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 2 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 


     case R.id.bD3: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 3 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD4: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 4 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD5: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 5 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD6: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 6 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD7: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 7 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD8: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 8 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD9: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 9 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD10: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 10 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD11: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 11 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD12: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 12 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD13: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 13 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD14: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 14 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD15: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 15 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD16: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 16 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 

     case R.id.bD17: 

     { 
      Toast.makeText(getActivity(), "Hai cliccato Regola 17 in Reg11 ", Toast.LENGTH_SHORT).show(); 

      break; 
     } 


    } 

} 

}

qualcuno può aiutarmi?

EDIT 2

ho trovato la soluzione, controllare la mia risposta qui sotto per il codice.

Grazie a tutti per le vostre risposte.

risposta

7

Ok ragazzi, problema risolto!

Questo è il codice che uso per aprire un file PDF, memorizzato su memoria esterna:

File pdfFile = new File(Environment.getExternalStorageDirectory(),"namePdfFile.pdf");//File path 
      if (pdfFile.exists()) //Checking for the file is exist or not 
      { 
       Uri path = Uri.fromFile(pdfFile); 
       Intent objIntent = new Intent(Intent.ACTION_VIEW); 
       objIntent.setDataAndType(path, "application/pdf"); 
       objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(objIntent);//Staring the pdf viewer 
      } else { 

       Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show(); 

      } 
3

Le app di terze parti non possono accedere alle risorse tramite gli URL file:///android_asset.

È possibile:

  • Prova utilizzando my StreamProvider, per avere una ContentProvider nella vostra applicazione che può servire il file PDF direttamente da beni o

  • Usa FileProvider dal pacchetto di supporto Android, dopo aver copiato il file dalle risorse all'archiviazione interna, come dimostrato in this sample app o

  • Copia il file nella memoria esterna e utilizza un Uri creato da Uri.fromFile() per puntare a quella copia

+0

Ci dispiace, ma io sono un principiante, e non so come usare https: // github.com/commonsguy/cwac-provider. Puoi gentilmente darmi istruzioni passo-passo? –

+0

@AndreyVedishchev: Se sei un principiante, ti consiglio di andare con il terzo punto nella mia risposta. – CommonsWare

+0

Ok ma come si fa? –

1

Aggiungi il permesso e controllare ancora:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

a quanto pare, c'è un problema con l'accesso al file.

Prova ad aprire un altro file pdf e facci sapere qual è il registro.

ed inoltre penso che non è possibile utilizzare questo: file:///android_asset

e dare un'occhiata a questo:

Scegliere il file con ExternalStorageDirectory:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename); 
Intent target = new Intent(Intent.ACTION_VIEW); 
target.setDataAndType(Uri.fromFile(file),"application/pdf"); 
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 

Intent intent = Intent.createChooser(target, "Open File"); 

Da:https://stackoverflow.com/a/17453242/4945820

con un patrimonio Cartella:

e qui è il codice, se si utilizza questo con Assets cartella!

File file = new File("file:///android_asset/example.pdf"); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
startActivity(intent); 

e quindi aggiungere sopra permesso e verificare di nuovo con il codice di Assets. Inoltre, verifica: https://stackoverflow.com/q/28032029/4945820

+0

Ho sostituito il mio codice con il proprio e aggiunto le autorizzazioni di cui sopra. Sfortunatamente, quando sostituisco "+ filename" con il nome di un file PDF, ad esempio "regola11_2.pdf", è colorato in rosso e ottengo un "Impossibile risolvere il simbolo" regola11_2.pdf "". Puoi dirmi cosa ho fatto di sbagliato? –

+0

Modifica e Aggiornato. Dovresti usare la seconda parte dei codici (con Risorse) – developerdroid

+0

Niente ... sta ancora dando gli stessi messaggi ... –

2

Impostazione dei dati come "file:///" + filePath ha lavorato per me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filePath)); 
intent.setDataAndType(Uri.parse("file:///" + filePath), "application/pdf"); 
context.startActivity(intent); 
0

Ho avuto lo stesso problema, dopo ore che trattano il problema mi sono reso conto che ho perso per aggiungere "/" tra il percorso del file e il nome del file.

Quindi il file non è stato trovato e ho "Impossibile accedere a questo file Controllare la posizione o la rete e riprovare." Messaggio.

Spero che questo aiuto a qualcuno;)

0

Il mio problema è stato risolto dopo l'aggiunta di questa autorizzazione :)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />