Implementation of WebDAV client on android - android

I am using jakarta/slide project for implementing webDAV client on my android device.
I got the all necessary jar files into external library,
my code:
package com.android.webdav;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.httpclient.HttpException;
import org.apache.util.HttpURL;
import org.apache.webdav.lib.WebdavResource;
import android.app.Activity;
import android.os.Bundle;
public class Webdav extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpURL hrl = new HttpURL("serverUrl");
hrl.setUserInfo("username", "password");
WebdavResource wdr = new WebdavResource(hrl);
File fn = new File("remote-file");
wdr.getMethod(fn);
File LocFile = new File("mnt/sdcard/test/");
wdr.putMethod(LocFile);
wdr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but I am getting error,
java.lang.NoClassDefFoundError: org.apache.webdav.lib.WebdavResource
above class already added in jar.
Required help.
Thanks

Sardine + http://code.google.com/p/httpclientandroidlib/ does not work, because httpclientandroidlib has renamed all package names. See android sardine + httpclientandroidlib -> new package names

Sardine + http://code.google.com/p/httpclientandroidlib/
http://sardine.googlecode.com/

You can use https://github.com/yeonsh/Sardine-Android.

Related

XML simple parsing

I have a question about parsing (Android Studio). It is not about something in particular. My code just doesn't run. No errors. I want to be able to press a button and show a specific text, parsed from an XML file.
For now, i'll omit the button part and throw you the codes just for printing this text on a humble textview
XML CODE (app/src/main/assets follder. articles.xml)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE articles[
<!ELEMENT articles ANY>
<!ELEMENT article ANY>
<!ATTLIST article ID ID #IMPLIED> ]>
<articles>
<article ID="a1">TEST
</article>
<article ID="a2">1.TEST2
</article>
CLASS CODE
package com.blah.blah;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
TextView textView;
String stringArticle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager = this.getAssets();
InputStream inputStream = null;
try {
// Loads your XML file as an InputStream
inputStream = assetManager.open("articles");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element article = doc.getElementById("a1");
String stringArticle = article.getTextContent();
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringArticle);
} catch (IOException e) {
// Exception Handling Code
e.printStackTrace();
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
I haven't tried the techniques that return you a Nodelist, because I dont want to iterate over anything. I find it useless for my project. What I want is something extremely primitive. It's like those simple bible apps. You press the button with the verse and the corresponding text pops up. That simple.
And again, no errors at all! Just not working. I think the TRY part is not executed. Because it gives me the default 'hello world' text on the TextView. But, once i put the
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringarticle);
lines after the TRY/CATCH blocks, I just get an empty TextView.
TY!
You can place your XML file in "app/src/main/assets" directory. After that you can easily access your XML file via "AssetManager" class.
You can use below code as a reference:-
AssetManager assetManager = this.getAssets();
InputStream inputStream = null;
try {
// Loads your XML file as an InputStream
inputStream = assetManager.open("articles.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element article = doc.getElementById("1");
String stringarticle = article.getTextContent();
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringarticle);
} catch (IOException e) {
// Exception Handling Code
e.printStackTrace();
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
Just Remember to place your file in mentioned directory, otherwise "AssetManager" class won't be able to read it.
Cheers !!

java.io.FileNotFoundException only occurs when run inside AsyncTask

I have an odd problem; if I run this code I get a java.io.FileNotFoundException: https://graph.facebook.com/debug_token?input_token=1234&access_token=1234. This only occurs when I call client.getInputStream() inside my AsyncTask. Click the link: it clearly works.
Let's call this case 1.
Now, when I run the exact same code outside of my AsyncTask, I get a NetworkOnMainThreadException, but client.getInputStream() works...
Consider this case 2.
I know why I get the NetworkOnMainThreadException in case 2, but I don't understand why the FileNotFoundException only happens in case 1, and not in case 2. The code is identical! I've been looking at this for hours and I just don't know what I am doing wrong.
EDIT: apperently the FileNotFoundException occurs because of an error response code. I figured this out by getting the error stream with .getErrorStream() when the exception occurs.
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
public class Temp {
private String getResponse(InputStream stream){
Scanner s = new Scanner(stream).useDelimiter("\\A");
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
public void run(String url){
URL uri;
HttpsURLConnection client = null;
try {
uri = new URL(url);
client = (HttpsURLConnection) uri.openConnection();
client.setReadTimeout(15*1000);
} catch (IOException e) {
e.printStackTrace();
}
new RetrieveStream().execute(client);
}
private class RetrieveStream extends AsyncTask<HttpsURLConnection, Void, String> {
private String returnString = null; //don't change this!
HttpsURLConnection client;
#Override
protected String doInBackground(HttpsURLConnection... client) {
try {
this.client = client[0];
InputStream stream = this.client.getInputStream();
Log.d(getClass().getSimpleName(), "response: "+getResponse(this.client.getInputStream()));
} catch (FileNotFoundException e) {
Log.d(getClass().getSimpleName(), "error output: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
} catch (IOException e) {
Log.d(getClass().getSimpleName(), "error: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
}
this.client.disconnect();
return returnString;
}
protected void onPostExecute(String output) {
Log.d(getClass().getSimpleName(), "output: "+output);
}
}
}
i am not deep into android development, but since the Thread seem to be aware of connections (implied by "NetworkOnMainThreadException"), i'd suggest to handover the URL instance to your AsyncTask and open the connection there, instead of hand over the client.
Apart from this, by reading the api, i'd expect a
client.connect();
before
client.getInputStream();
get's called.
References:
https://developer.android.com/reference/java/net/URL.html#openConnection()
https://developer.android.com/reference/java/net/URLConnection.html#getInputStream()
It's not very clear why the FileNotFoundException occurs, but I was able to get the response with .getErrorStream() instead of .getInputStream(). My question is edited accordingly. Please ignore the other answers, they provide no solutions.

Jar not found error in Android

In the following code below i have importted the jsch jar by clicking on Project properties and by adding the "add external jar button" also have added into the ant global path from the following link Add external jar but when i run the program i still get the "java.lang.NoClassDefFoundError: com.jcraft.jsch.JSch"
package android_jsch.com;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import com.jcraft.jsch.*;
import android.os.Bundle;
import android.widget.EditText;
public class Android_jschActivity extends Activity {
EditText ip,username,password;
#Override
public void onCreate(Bundle savedInstanceState) {
List<String> commands = new ArrayList<String>();
commands.add("touch /tmp/test1.txt");
commands.add("touch /tmp/test2.txt");
commands.add("touch /tmp/test3.txt");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rd);
try {
JSch jsch = new JSch();
session.connect();
Channel channel=session.openChannel("shell");//only shell
channel.setOutputStream(System.out);
PrintStream shellStream = new PrintStream(channel.getOutputStream()); // printStream for convenience
channel.connect();
for(String command: commands) {
shellStream.println(command);
shellStream.flush();
}
Thread.sleep(5000);
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.err.println("ERROR: Connecting via shell to "+ip.getText().toString());
e.printStackTrace();
}
}
private static void setUpHostKey(Session session) {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
}
}
You should specify that the jar must be exported when building apk: in "Java Build Path" > "Order and Export" tab, fill the checkbox corresponding to your jar.

Android bluetooth exception

Ok, I will try one more time.
I have a device sdptool in ubuntu the following is stated from my device:
# sdptool browse C0:1B:DC:1F:E2:F1
Browsing C0:1B:DC:1F:E2:F1 ...
Service Name: OBEX Object Push
Service RecHandle: 0x10000
Service Class ID List:
"OBEX Object Push" (0x1105)
Protocol Descriptor List:
"L2CAP" (0x0100)
"RFCOMM" (0x0003)
Channel: 9
"OBEX" (0x0008)
Profile Descriptor List:
"OBEX Object Push" (0x1105)
Version: 0x0100
As you can se the device does support the RFCOMM protocol, and OBEX for file transfer. I have a simple code for my android app which tries to connect to this device over a insecure RFCOMM channel, just for no user interaction. I want to connect to this device, so Iam using the device mac-address for connection, and the socket is ready, logcat says so.
But I only get the error:
Connection refused
Have in mind that the mac-address in the java code is different from the following listed above.
So here is my code:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//MY_UUID = new UUID(0x0100 , 0x1000);
// MY_UUID = UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812");
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BluetoothSocket tmp = null;
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:1B:DC:0F:EC:7E");
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InvocationTargetException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
try {
tmp.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Socket closed!" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
boolean con = tmp.isConnected();
if(con)
Toast.makeText(getApplicationContext(), "Connection was made!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Connection was not made!", Toast.LENGTH_LONG).show();
}
});
}
}
I've read several places that it should work by un-pairing and pair again, but this doesn't solve my problem.
Well, your question is over a month old, but in case you're still looking for the answer, here's one:
sdptool indicates that your RFCOMM channel is 9, but in your code you have:
tmp = (BluetoothSocket) m.invoke(device, 1);
Instead of 1 as your last argument, try 9 (if that doesn't work, try other integers, like 2 through 15).
You may also want to check out this answer.
There seem to be many variations of this question on Stack, but not a lot of understanding of the "standard" recommended code (i.e., the bluetooth chat sample modified with the lines that define and invoke "Method m")--I know because I'm one of those people who struggled with this. I was trying to connect my phone to my MacBook, and got the "connection refused" message until I realized that I needed to use 5 in the line of code above.

Phonegap setting wallpaper from www assets? Android

I'm building a phonegap app for Android and need a way to set wallpapers from a .jpg included in the www directory of the app using javascript. How would I go about building a phonegap plugin that works with resources in my phonegap apps www folder?
just read file from asset folder. with Plugin
import java.io.IOException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;
import android.app.WallpaperManager;
import android.content.Context;
public class testPlugin extends Plugin {
public final String ACTION_SET_WALLPAPER = "setWallPaper";
#Override
public PluginResult execute(String action, JSONArray arg1, String callbackId) {
PluginResult result = new PluginResult(Status.INVALID_ACTION);
if (action.equals(ACTION_SET_WALLPAPER)) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance((Context) this.ctx);
try {
InputStream bitmap=null;
bitmap=getAssets().open("www/img/" + arg1.getString(0));//reference to image folder
Bitmap bit=BitmapFactory.decodeStream(bitmap);
wallpaperManager.setBitmap(bit);
result = new PluginResult(Status.OK);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = new PluginResult(Status.ERROR, e.getMessage());
}
}
return result;
}
}
this is javascript file test.js
var TestPlugin = function () {};
TestPlugin.prototype.set = function (ms, successCallback, failureCallback) {
// navigator.notification.alert("OMG");
return cordova.exec(successCallback, failureCallback, 'testPlugin', "setWallPaper", [ms]);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("test", new TestPlugin());
})
and main file call Plugin with imagefilename
window.plugins.test.set("imageFileName.jpg",
function () {
navigator.notification.alert("Set Success");
},
function (e) {
navigator.notification.alert("Set Fail: " + e);
}
);
;
with android device permission
<uses-permission android:name="android.permission.SET_WALLPAPER" />
and plugin.xml
<plugin name="testPlugin" value="com.android.test.testPlugin"/>

Categories

Resources