Using MonoDroid in Visual Studio and an emulator, I am trying to copy a asset, "db.sqlite" from the assets folder to the SD card so that I can open the database for read/write.
When I run the app, it dies. MonoDroid is not giving me any debug info.
string destPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.Personal), "db.sqlite");
if (!File.Exists(destPath))
using (Stream stream = Assets.Open("db.sqlite"))
{
stream.CopyTo(File.Create(destPath));
stream.Close();
}
Check the Android Debug Log:
http://android.xamarin.com/Documentation/Guides/Android_Debug_Log
Try saving the file with database file .mp3 extension and then use the following script to copy it to SD card
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs());
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".mp3")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
Code that worked for me (it copies recursively file or directory and all subdirectories ):
private void copy(string SourcePath){
string[] list = Assets.List(SourcePath);
if (list.Length > 0) {
Directory.CreateDirectory(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath);
foreach (string dirPath in Assets.List(SourcePath)){
string newPath = SourcePath + "/" + dirPath;
copy(newPath);
}
}
else{
Assets.Open(SourcePath).CopyTo(new FileStream(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath, FileMode.OpenOrCreate));
}
}
Usage: copy(path_relative_to_assets_root);
Related
I am writing a program to count words in a file. I am facing problems while parsing .tex files.
This code need to go on a website where it has to count words from the file that is being uploaded. I have managed to do it but I am looing for some better solutions
case "application/x-tex": // Avoid words with '\' and count
Scanner sc1;
try {
sc1 = new Scanner(new URL(URLPath).openStream());
while (sc1.hasNext()) {
String str = sc1.next();
if (!str.contains("\\")) {
System.out.print(str + " ");
wordCount++;
}
}
sc1.close();
} catch (IOException e) {
System.out.println("There was a problem while reading File on the URL");
break;
// e.printStackTrace();
}
if (wordCount <= 0) {
System.out.println("Total count is " + wordCount
+ ". The uploaded File is either empty or it consists of Images only");
} else {
System.out.println("");
System.out.println("**********");
System.out.println("Word Count: " + wordCount);
System.out.println("**********");
System.out.println("");
}
break;
I am expecting a String output which I could further use to count words.
// Trigger perl script
URL website = new URL(URLPath);
Path path = Paths.get("myfile.tex");
bufferFiles.add(new File("myFile.tex"));
try (InputStream in = website.openStream()) {
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
}
URL texcount = new URL("https://papertrue.s3.us-west-1.amazonaws.com/draft/77e3c992-b70f-4711-8b9b-eaf390617bb8");
Path path1 = Paths.get("texcount.pl");
bufferFiles.add(new File("texcount.pl"));
try (InputStream in = texcount.openStream()) {
Files.copy(in, path1, StandardCopyOption.REPLACE_EXISTING);
}
wordCount = 0;
Process process;
try {
process = Runtime.getRuntime().exec("/etc/papertrue/texcount.pl myfile.tex");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
String tem[] = line.split(":\\s");
log.debug(tem[tem.length - 1]);
try {
wordCount += Integer.parseInt(tem[tem.length - 1]);
} catch (Exception e) {
}
}
process.waitFor();
if (process.exitValue() == 0) {
log.debug("Command Successful");
} else {
log.debug("Command Failure");
}
log.debug(wordCount);
} catch (IOException e) {
log.debug("There was a problem while reading File on the URL");
e.printStackTrace();
break;
}
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
System.out.println("status"+status);
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My attachment are stored in machine dependent location. How I change it into my own location? (ex:-war/uploads/..). Now path shows my machine name also.(ex:-/home/name/NetBeansProjects/prjname/dist/wldeploy/prjname/prjname-war.war/uploads/image.jpg)
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
I am working on a blackberry application in which I need to hit a url create a connection and write a file and save that to SDcard. Currently I am following this particular code. But while creating FileOutputStream object it throws CLassCastException. I am struggling with this.
public void run() {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
OutputStream fos=null;
int rc;
try {
httpConnection = new HttpConnectionFactory()
.getHttpConnection("http://faultcode.techvalens.net/PDF/DrawingSample.PDF");
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream is = httpInput;
FileConnection fconn=(FileConnection)Connector.open("file:///SDCard/Test.txt",
Connector.READ_WRITE);
if(!fconn.exists())
fconn.create();
System.out.println(fconn.exists());
fos = new FileOutputStream( File.FILESYSTEM_PATRIOT, "Test.txt" );
// byte[] b = IOUtilities.streamToBytes(inp);
byte[] buffer = new byte[702];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
} catch (Exception ex) {
System.out.println("URL Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
the above code i am using.
Please let me know what is my mistake.
THanx in advance...!!!
The task was basic but created an unforgettable concept for me. Below is the code now i am using, its the best if i need to download any type file from URL.
public void run(){
GetURLWebService _webService = new GetURLWebService(methodName,elecID,pdfType,performedBy,notes);
String pdfURL = _webService.getWebServiceData();
_pdfURL = pdfURL;
System.out.println("Download the pdf...!!!");
try {
int chunkIndex = 0;
int totalSize = 0;
/*
* File connection
*/
FileConnection file =(FileConnection)Connector.open(localFile);
if (!file.exists()) {
file.create();
}
file.setWritable(true);
OutputStream out = file.openOutputStream();
/*
* HTTP Connections
*/
String currentFile = _pdfURL + connectionType();
//log("Full URL: " + currentFile);
HttpConnection conn;
InputStream in;
int rangeStart = 0;
int rangeEnd = 0;
while (true) {
// log("Opening Chunk: " + chunkIndex);
conn = (HttpConnection) Connector.open(currentFile,
Connector.READ_WRITE, true);
rangeStart = chunkIndex * chunksize;
rangeEnd = rangeStart + chunksize - 1;
// log("Requesting Range: " + rangeStart +
// "-" + rangeEnd);
conn.setRequestProperty("Range", "bytes=" +
rangeStart + "-" + rangeEnd);
int responseCode = conn.getResponseCode();
if (responseCode != 200 && responseCode != 206)
{
// log("Response Code = " + conn.getResponseCode());
break;
}
// log("Retreived Range: " + conn.getHeaderField("Content-Range"));
in = conn.openInputStream();
int length = -1;
byte[] readBlock = new byte[256];
int fileSize = 0;
while ((length = in.read(readBlock)) != -1) {
out.write(readBlock, 0, length);
fileSize += length;
Thread.yield(); // Try not to get cut off
}
totalSize += fileSize;
// log("Chunk Downloaded: " + fileSize + " Bytes");
chunkIndex++; // index (range) increase
in.close();
conn.close();
in = null;
conn = null;
/*
* Pause to allow connections to close and other Threads
* to run.
*/
Thread.sleep(1000);
}
// log("Full file downloaded: " + totalSize + " Bytes");
out.close();
file.close();
// log("Wrote file to local storage");
} catch (Exception e) {
System.out.println(e.toString());
}
}
private String connectionType() {
switch (conn) {
case 1:
return ";deviceside=false";
case 2:
return ";deviceside=true;interface=wifi";
default:
return ";deviceside=true";
}
}
Im having difficulties with the HttpConnection posting data to my server. The first time everything goes well. The second time it says; 'Stream already open', but i close everything after the response.
Here is my code:
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.*;
import java.io.*;
class GetSnowheights
{
HttpConnection http = null;
QualifiedCoordinates q = null;
public String result = "Geen data";
private boolean running;
public GetSnowheights(QualifiedCoordinates q) {
try
{
/*
this.http = (HttpConnection)Connector.open("http://www.diamond4it.nl/bb/");
this.http.setRequestMethod(HttpConnection.POST);
this.http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
*/
//Internet.getInstance();
this.http = Internet.getConnection();
}catch(Exception err){
err.printStackTrace();
}
this.q = q;
this.result = "Running";
}
public void GetResult(){
StringBuffer sb = new StringBuffer();
this.result = "GetResult";
if(this.http != null){
OutputStream os = null;
InputStream is = null;
try
{
//Send request
os = this.http.openOutputStream();
String data = "lat=1&lng=1";
//String data = "lat=" + this.q.getLatitude() + "&lng=" + this.q.getLongitude();
os.write(data.getBytes());
os.flush();
os.close();
this.result = "dataSend";
//Check response and read data
int res = this.http.getResponseCode();
this.result = "Result: " + res;
if(res == 200){
is = this.http.openInputStream();
int ch;
// Check the Content-Length first
long len = this.http.getLength();
if(len!=-1) {
for(int i = 0;i<len;i++){
if((ch = is.read())!= -1){
sb.append((char)ch);
}
}
} else {
// if the content-length is not available
while ((ch = is.read()) != -1){
sb.append((char)ch);
}
}
is.close();
}
this.result = sb.toString();
}catch(Exception err){
//err.printStackTrace();
this.result = err.toString() + "\r\n" + err.getMessage();
}finally{
if(is != null){
try{
is.close();
}catch(Exception err){
err.printStackTrace();
}
}
if(os != null){
try{
//os.flush();
os.close();
}catch(Exception err){
err.printStackTrace();
}
}
/*
if(http != null){
try{
http.close();
}catch(Exception err){
err.printStackTrace();
}
}
*/
}
}else{
this.result = "No connection";
}
}
}
2 ideas:
Why have you commented out the http.close() in finally block? We should always close HttpConnections.
Don't you call GetResult() from several threads simultaneously? If yes, then make the method synchronized by adding synchronized keyword in its definition.
P.S. I find the design of the class a bit misleading. It's very easy to make a mistake by incorrect usage of it. I'd combine GetSnowheights and GetResult into the only synchronized method.