.I followed this tutorial and getting errors "PARSING ERROR THERE IS A PROBLEM PARSING THE PACKAGE". I have check the result in Android Device Samsung Galaxy S3.
package com.mrfs.android.surveyapp.activities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class ApkFileAsync extends Activity
{
UpdateApp updateAppInstance;
#Override
public void onCreate(Bundle savedBundleInstance)
{
super.onCreate(savedBundleInstance);
updateAppInstance = new UpdateApp();
updateAppInstance.setContext(getApplicationContext());
updateAppInstance.execute("http://demo.ingresssolutions.com/proposalmanagement/services/user/getApkFile");
}
private class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file,"surveyapp.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
/* Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/ // without this flag android returned a intent error!
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}}
}
I am getting this error after Complete Action using dialog when trying to press either PACKAGE INSTALLER or VERIFY AND INSTALL in both cases same error.
Change your manifes to like
This should work fine i think.. If not worked please post your tutorial link i missed it.. i need to check it.. and i will update answer...
and also mention how you are installing app wether by eclipse or by some other process like importing apk... IF importing apk to real device means please check ur device version, If its s3 mans it has ICS api level includes 14 or 15 so change that.. if its jellly bean means you can use up to 18
Related
I have been trying to get some very simple code to work which should read an online file and print the contents of that file in the log. At first I didn't know that it needed to be handled in a seperate thread so I left it in the onCreate Method. Now I put it into a seperate Thread with the help of this question: How to use separate thread to perform http requests but the app still crashes! Since I'm desperate to get this working so I can keep on learning how to program this app, I will insert the exact code I used:
package com.dan6erbond.schoolhelper;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private String link = "https://dan6erbond.github.io/I1A/Documents/Zusammenfassungen/Zusammenfassungen.json";
String content;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.i("TAG", content);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread downloadFile = new Thread(new Runnable(){
#Override
public void run(){
try {
URL url = new URL(link);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
content += str;
}
Log.i("TAG", content);
in.close();
} catch (Exception e) {
Log.i("TAG", "Error occured!");
}
handler.sendEmptyMessage(0);
}
});
downloadFile.start();
}
}
In the log the error message is being sent:
01-05 07:40:33.320 9601-9622/com.dan6erbond.schoolhelper I/TAG: Error occured!
I'd be really happy if someone could help me with this problem. It's probably very simple but I just started coding in Android Studio so I'm really new to this.
I just needed to add the INTERNET permission. I figured that out by printing the error message:
Log.i("TAG", e.getMessage());
Which resulted in this:
01-05 08:05:10.806 11815-11838/com.dan6erbond.schoolhelper I/TAG: Permission denied (missing INTERNET permission?)
I just added this to the Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Thanks everyone for your help!
I want to share a mp3 file to whatsapp.
I found this question on Stack Overflow, but the accepted answer does not work for me. If I try to share it with whatsapp it says "Sharing failed, please try again":
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {
e.printStackTrace();}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
share.setType("audio/mp3");
startActivity(Intent.createChooser(share, "Shared"));
Here is the full MainActivity.java:
package com.example.aaron.sharetest;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
Button shareBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/com.example.aaron.sharetest/files");
File sharefile= new File(FILES_PATH, "sound.mp3") ;
putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile));
shareBtn = (Button)findViewById(R.id.shareBtn);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
finish();
}
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.bibikurz);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
share.setType("audio/mp3");
startActivity(Intent.createChooser(share, "Shared"));
}
});
}
}
Of course I wrote this line in my Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
What do I have to do to share the mp3 file to whatsapp, etc?
I tried so many accepted answers, but no one of them worked for me.
This is what I get in my LogCat:
06-23 02:41:17.589 23924-23924/? W/Bundle: Key android.intent.extra.STREAM expected ArrayList but value was a android.net.Uri$StringUri. The default value <null> was returned.
06-23 02:41:17.659 23924-23924/? W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: android.net.Uri$StringUri cannot be cast to java.util.ArrayList
at android.os.Bundle.getParcelableArrayList(Bundle.java:838)
at android.content.Intent.getParcelableArrayListExtra(Intent.java:5481)
at com.whatsapp.ContactPicker.k(ContactPicker.java:623)
at com.whatsapp.ContactPicker.onCreate(ContactPicker.java:338)
at android.app.Activity.performCreate(Activity.java:6367)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2511)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1375)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5621)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Android 6.0 Marshmallow (API 23) or later. If this is the case, you mustimplement runtime permissions
Use file path and check memory card
File FILES_PATH = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.examples(your package )/files");
File sharefile= new File(
FILES_PATH,
"demo.mp3") ;
putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile))
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w(TAG, "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
finish();
}
My "sound.mp3" file is located in the raw folder.
Your first two samples will not work, as they have nothing to do with a raw resource. They share a file that does not exist, from a directory that might also not exist.
But here I dont know what "ContextID" or "ResouceID" is.
If this code is going where your first two code snippets went, ContextID can be replaced with this. If you are trying to share res/raw/sound.mp3, then ResourceID is R.raw.sound.
I have a problem to get .xml data from website and parse to android application, i have try many suggestion but never work. It works fine when i open file in assets folder, but when i try to get from url, it show nothing
This is my Activity Class
package com.android.baliweather;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
public class Prakiraan extends Activity {
/** Called when the activity is first created. */
private ListView listView;
private TextView judul;
private String URL_MAIN = "http://localhost/android/propinsi_17_1.xml";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prakiraan_cuaca);
judul = (TextView) findViewById(R.id.menu1);
listView = (ListView) findViewById(R.id.listview);
bindDataToListing();
}
private void bindDataToListing() {
try {
URL url = new URL("http://localhost/android/propinsi_17_1.xml");
URLConnection connection = url.openConnection();
//URLConnection connection = url.openConnection();
//HttpURLConnection httpConnection = (HttpURLConnection)connection;
//InputStream in = httpConnection.getInputStream();
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
XMLParser pc = new XMLParser();
xmlReader.setContentHandler(pc);
//InputStream is = getAssets().open("propinsi_17_1.xml");
//InputStream is = new URL(URL_MAIN).openStream();
xmlReader.parse(new InputSource(connection.getInputStream()));
BindingData bindingData = new BindingData(this, pc.kota, pc.cuaca, pc.suhuMin, pc.suhuMax, pc.kelembapanMin, pc.kelembapanMax, pc.kecepatanAngin, pc.arahAngin);
listView.setAdapter(bindingData);
}
catch (Exception e) {
e.getMessage();
}
}
}
I think the problem only on this class, but i have no idea which one. Please help
It might be android.os.NetworkOnMainThreadException - you're trying to do time-heavy task in a UI thread and the system is preventing you from doing it (you can possibly see this in your logcat). You can implement AsyncTask in order to do it in the background thread.
It may also be that you forgot to add the permission in a manifest file - <uses-permission android:name="android.permission.INTERNET" />
I am trying to retrieve a reference to a file stored in the assets directory to a file named myfile.pdf. I have tried to do it as follows:
File file = new File("android_assest/myfile.pdf);
Log.d("myTag", "" + file.isFile());
Somehow, I get false when the myfile.pdf do exists in the assets directory. I verified it using getAssets().list("") and Log.d() each element in the returned array.
More of which, I am trying to get a reference to a PDF file and then use any PDF viewer, which is already installed on the device, in order to view the PDF.
I guess that since the previous issue (retrieving a reference to the file) returns false then the next snipped code fails:
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("file:///android_asset/myfile.pdf"));
startActivity(i);
Anyone has a clue why I am unable to retrieve a reference to the file? and why I cannot use already installed PDF viewer to display a PDF (after retrieving a reference to the PDF file)?
Thanks.
As Barak said you can copy it out of assets to internal storage or the SD card and open it from there using inbuilt pdf applications.
Following Snippet will help you.
(I have updated this code to write to and read files from internal storage.
But i dont recommend this approach because pdf file can be more than 100mb in size.
So its not recommended to save that huge file into internal storage
Also make sure while saving file to internal storage you use
openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
Then only other applications can read it.
Check following snippet.
package org.sample;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class SampleActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "git.pdf");
try
{
in = assetManager.open("git.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/git.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
Make sure to include
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in manifest
You can't do it like that. There is no directory structure in an apk, it is just data. The framework knows how to access it (getAssets), but you cannot look for it as a file in a directory.
You can open it as an input stream...
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(myfile.pdf)));
Or you can copy it out of assets to internal storage or the SD card and access it there.
like say Vipul Shah, but in the case for external.
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyReadAssets();
}
private void copyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs";
File fileDir = new File(strDir);
fileDir.mkdirs(); // crear la ruta si no existe
File file = new File(fileDir, "example2.pdf");
try
{
in = assetManager.open("example.pdf"); //leer el archivo de assets
out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
change parts of code like these:
out = new BufferedOutputStream(new FileOutputStream(file));
the before example is for Pdfs, in case of to example .txt
FileOutputStream fos = new FileOutputStream(file);
I am attempting to use java FileInputStream to write some strings to a text file that will be stored on the android internal storage. However my virtual device keeps throwing an exception and I am not sure what or where I should be looking as the DDMS log cat function does not give me any useful information. I am using a try/catch structure with a stack trace print as shown below. I am not very familiar with the debug function in relation to android and I am not sure where else I can look to find out what is going on. Code is below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText)findViewById(R.id.textView1);
Button saveBtn = (Button)findViewById(R.id.button1);
Button loadBtn = (Button)findViewById(R.id.button2);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try{
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved message---
Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[]inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer))>0){
//---convert the char to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been read---
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
}
}
did you set your permissions in your manifest for writing?
and is your device a droidx (which when you plug in the USB cable, unmounts the external storage, making it inaccessible).
Why not run the debugger and put in debug points and see how far it gets before it crashes?