Jar not found error in Android - 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.

Related

NanoHTTPD server on desktop

I'm trying to serve a small file on my desktop using NanoHTTPD. The server starts fine but due to some unknown reason, it is unable to serve files. The same program works fine in Android. Can anyone give me some pointers? It's being more than an hour but I've got no clue. Here is my desktop version of NanoHTTPD server:
package com.desktopserver;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Map;
import com.desktopserver.NanoHTTPD.Response.Status;
public class MainClass {
static int PORT = 8080;
static WebServer MyServer;
static FileInputStream fis;
static BufferedInputStream bis;
public static void main(String[] args) {
MyServer = new WebServer();
try {
MyServer.start();
System.out.println("Webserver Started # PORT:8080");
} catch (IOException e) {
e.printStackTrace();
}
}
public static class WebServer extends NanoHTTPD {
String MIME_TYPE;
public WebServer() {
super(PORT);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
try {
File file=new File("/home/evinish/Music/Meant_to_live.mp3");
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
MIME_TYPE= URLConnection.guessContentTypeFromName(file.getName());
System.out.println("\nMIME TYPE: "+MIME_TYPE);
System.out.println("\nFILE NAME: "+file.getName());
} catch (IOException ioe) {
System.out.println("File IO Exception");
}
return new NanoHTTPD.Response(Status.OK, MIME_TYPE, bis);
}
}
}
I do get this output, but that's it:
Webserver Started # PORT:8080
What am I missing here? Thanks a lot for your help.
Because you don't use "ServerRunner" class. ServerRunner hold you server to until any key press.
But in real application this don't work you want some change in NanoHTTPd file
line no 196 to
myThread.setDaemon(false);

Android saving logs on every run for crash report [duplicate]

This question already has answers here:
How do I obtain crash-data from my Android application?
(30 answers)
Closed 5 months ago.
I'm currently developing an android app. I noticed a very rare error which leeds to a crash of my app. Unfortunately, I had my smartphone never connected to my pc when it occured. So, is there a way to automatically save all logs (and especially the thrown runtimeexceptions) to a file when my app starts, so that I can copy this file to my pc and analyse the error? The file should be overwritten on every start of my app, so that it contains only the logs of the last run... How can I achieve that?
regards
You can find help by following this link Writing crash reports into device sd card
You don't need to add external library.
import com.wordpress.doandroid.Training.R;
import android.app.Activity;
import android.os.Bundle;
public class CaptureExceptionActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets the default uncaught exception handler. This handler is invoked
// in case any Thread dies due to an unhandled exception.
Thread.setDefaultUncaughtExceptionHandler(new CustomizedExceptionHandler(
"/mnt/sdcard/"));
String nullString = null;
System.out.println(nullString.toString());
setContentView(R.layout.main);
}
}
And the Handler implementation
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;
import android.util.Log;
public class CustomizedExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
private String localPath;
public CustomizedExceptionHandler(String localPath) {
this.localPath = localPath;
//Getting the the default exception handler
//that's executed when uncaught exception terminates a thread
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(Thread t, Throwable e) {
//Write a printable representation of this Throwable
//The StringWriter gives the lock used to synchronize access to this writer.
final Writer stringBuffSync = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringBuffSync);
e.printStackTrace(printWriter);
String stacktrace = stringBuffSync.toString();
printWriter.close();
if (localPath != null) {
writeToFile(stacktrace);
}
//Used only to prevent from any code getting executed.
// Not needed in this example
defaultUEH.uncaughtException(t, e);
}
private void writeToFile(String currentStacktrace) {
try {
//Gets the Android external storage directory & Create new folder Crash_Reports
File dir = new File(Environment.getExternalStorageDirectory(),
"Crash_Reports");
if (!dir.exists()) {
dir.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
String filename = dateFormat.format(date) + ".STACKTRACE";
// Write the file into the folder
File reportFile = new File(dir, filename);
FileWriter fileWriter = new FileWriter(reportFile);
fileWriter.append(currentStacktrace);
fileWriter.flush();
fileWriter.close();
} catch (Exception e) {
Log.e("ExceptionHandler", e.getMessage());
}
}
}
Don't forget to add this permission in the manifest WRITE_EXTERNAL_STORAGE

How can i Load a jar file dynamically in an android application (4.0.3)

I have an android application which has to load dynamically class ,an undefined number of a jar class which implemented an interface.
In fact, I look at a directory and list all the jar files which are in this directory
I open the manifest of the jar file and find the associated class and list them.
And after, i instancied a dexClassLoader to load all the jar files and to find if the classes i have found in the manisfest implement my interface.
Like this I can have all the class which implemented my interface without knowing them at the begginning
To resume, i have a list of class jar which implement my interface but the list is unknown by my android application and by me. The list of jar class can changed each time i launch my application.
But when i tried to create the DexClassLoader it is failed. I have always a null pointer
DexClassLoader classLoader = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),dexOutputDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
To make my test i used the emulator. I have copied with my DDMS the jar files into the directory
/data/data/com.example.Myappli/JarFilesDirectory/*.jar
Notice that my jar file contents the dex file
I read a lot of thing about this. Some permissions issues
I have tried every thing but not found the solution
Can someone help me please !!!
here the content of a manifest of a jar file
Manifest-Version: 1.0
Module-Class: com.example.asktester.AskPeripheral
Here my code :
public class ModuleLoader {
private static List<URL> urls = new ArrayList<URL>();
private static List<String> getModuleClasses(String folder)
{
List<String> classes = new ArrayList<String>();
//we are listing the jar files
File[] files = new File(folder).listFiles(new ModuleFilter());
for(File f : files)
{
JarFile jarFile = null;
try
{
//we open the jar file
jarFile = new JarFile(f);
//we recover the manifest
Manifest manifest = jarFile.getManifest();
//we recover the class
String moduleClassName = manifest.getMainAttributes().getValue("Module-Class");
classes.add(moduleClassName);
urls.add(f.toURI().toURL());
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(jarFile != null)
{
try
{
jarFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
return classes;
}
private static class ModuleFilter implements FileFilter {
#Override
public boolean accept(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
}
private static ClassLoader classLoader;
public static List<IPeripheral> loadModules(String folder, Context CurrentContext) throws IOException, ClassNotFoundException
{
List<IPeripheral> modules = new ArrayList<IPeripheral>();
List<String> classes = getModuleClasses(folder);
final File dexInternalStoragePath = new File(CurrentContext.getDir("dex", Context.MODE_PRIVATE),"ask.dex");
File dexOutputDir = CurrentContext.getDir("dex", Context.MODE_PRIVATE);
final File dexClasses = new File(CurrentContext.getDir("dex", Context.MODE_PRIVATE),"ASK.jar");
DexFile dexFile = DexFile.loadDex(dexClasses.getAbsolutePath(), dexOutputDir.getAbsolutePath(), 0);
DexClassLoader classLoader = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),dexOutputDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
//Class<?> myClass = classLoader.loadClass("com.example.asktester.AskPeripheral");
if(IPeripheral.class.isAssignableFrom(myClass )){
Class<IPeripheral> castedClass = (Class<IPeripheral>)myClass ;
IPeripheral module = castedClass.newInstance();
modules.add(module);
}
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return modules;
}
I found the solution to my issue.
To load dynamically jar, classes which implement an interface in an android application, some jobs need to be done in the jar :
Create your own manisfest for the jar and put this information
Manifest-Version: 1.0
Module-Class: com.example.myjar.MyPeripheral
Export your jar using eclipse and put in parameter that it uses its own manisfest
Create the classes.dex associated to the jar
(this file is needed by the Dalvik VM, simply jar can not be read by the dalvik VM)
dx --dex --output=C:\classes.dex C:\MyJar.jar
Be carefull, the name of the dex file MUST BE classes.dex
Add the file classes.dex in the jar file
aapt add C:\MyJar.jar C:\classes.dex
You need also to have the right to write into the dalvik cache directory
adb shell chmod 777 /data/dalvik-cache
Do it each time, your relaunch your emulator
put this jar file into the emulator for example on the SDcard
Use a PathClassLoader to load the jar file
dalvik.system.PathClassLoader myClassLoader = new dalvik.system.PathClassLoader("/Sdcard/MyJar.jar", ModuleLoader.class.getClassLoader());
NB : the LogCat in Eclipse gives you precious information. Do not forget to look at its messages
Below, the code :
My interface :
package com.example.StandartPeripheral;
public interface IPeripheral {
public boolean Initialize();
public boolean configure();
public boolean execute();
public String GetName();
}
MyPeripheral which implements the interface
public class MyPeripheral implements IPeripheral {
//public static void main(String[] args) {}
private final String PeripheralName = "MyPeripheral";
public boolean Initialize()
{
System.out.println("Initialize ");
return true;
};
public boolean configure()
{
System.out.println("Configure !");
return true;
};
public boolean execute()
{
System.out.println("Execute !");
return true;
};
public String GetName()
{
return PeripheralName;
}
}
How to load dynamically the jar files
package com.example.ModuleLoader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import com.example.StandartPeripheral.IPeripheral;
public class ModuleLoader {
private static List<URL> urls = new ArrayList<URL>();
// to retrieve the unknown list of jar files contained in the directory folder
// in my case it was in the SDCard folder
// link to create a SDCard directory on the Eclipse emulator
// http://blog.lecacheur.com/2010/01/14/android-avoir-acces-a-une-carte-memoire-dans-lemulateur/
// retrieve the classes of all this jar files and their URL (location)
private static List<String> getModuleClasses(String folder)
{
List<String> classes = new ArrayList<String>();
//we are listing the jar files
File[] files = new File(folder).listFiles(new ModuleFilter());
for(File f : files)
{
JarFile jarFile = null;
try
{
//we open the jar file
jarFile = new JarFile(f);
//we recover the manifest
Manifest manifest = jarFile.getManifest();
//we recover the class name of our peripherals thanks to ours manifest
String moduleClassName = manifest.getMainAttributes().getValue("Module-Class");
classes.add(moduleClassName);
urls.add(f.toURI().toURL());
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(jarFile != null)
{
try
{
jarFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
return classes;
}
private static class ModuleFilter implements FileFilter {
#Override
public boolean accept(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
}
//This function loads the jar file into the dalvik system
// retrieves the associated classes using its name
// and try to know if the loaded classes are implementing our interface
public static List<IPeripheral> loadModules(String folder, Context CurrentContext) {
List<IPeripheral> modules = new ArrayList<IPeripheral>();
List<String> classes = getModuleClasses(folder);
int index = 0;
for(String c : classes)
{
try
{
dalvik.system.PathClassLoader myClassLoader = new dalvik.system.PathClassLoader(urls.get(index).toString(), ModuleLoader.class.getClassLoader());
Class<?> moduleClass = Class.forName(c, true, myClassLoader);
//check and cast to an interface, then use it
if(IPeripheral.class.isAssignableFrom(moduleClass))
{
#SuppressWarnings("unused")
Class<IPeripheral> castedClass = (Class<IPeripheral>)moduleClass;
IPeripheral module = (IPeripheral)moduleClass.newInstance();
modules.add(module);
}
index++;
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return modules;
}
}
It would also be a good idea to use the ClassLoader rather than the Dalvik path class loader:
ClassLoader cl = new DexClassLoader(url, ApplicationConstants.ref_currentActivity.getFilesDir().getAbsolutePath(), null, ModuleList.class.getClassLoader());
Where url is the location of the file you are loading "from".
ApplicationConstants.ref_currentActivity is simply an activity class - my implementation is fairly complicated due to dynamic modular loading - so I needed to keep track of it this way - but others can probably just use "this" if that class is already an activity.
The MAIN reason for using the class loader over the dalvik one - is that it doesn't require files to be written to cache, and therefore the permission chmod 777 /data/dalvik-cache is unrequired - and of course you also wouldn't need to pass this command from root on a rooted phone pro-grammatically either.
It's always best to not have users forced to root their phones, simply because your app requires it. Especially if your app is a more professional "meant-for-company-use-type" -.Work Policies against the use of rooted phones are usually in place too.
If anyone has any questions on modular loading - please feel free to ask.
The base of my current code is all thanks to Virginie Voirin, along with my own modifications. Good luck all!

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"/>

Implementation of WebDAV client on 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.

Categories

Resources