I am new to android development. I downloaded source file from the following link
"http://android-er.blogspot.in/2012/07/implement-custom-linearlayout-for.html", but while trying to run in emulator it shows
java.lang.NullPointerException at com.example.androidhorizontalscrollviewgallery.MainActivity.onCreate(MainActivity.java:27)
My MainActivity.java code is below:
package com.example.androidhorizontalscrollviewgallery;
import java.io.File;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
MyHorizontalLayout myHorizontalLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHorizontalLayout = (MyHorizontalLayout)findViewById(R.id.mygallery);
File targetDir=getDir("Pictures",Context.MODE_PRIVATE);
String targetPath=targetDir+ "/homepage/";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for(File f : files){
myHorizontalLayout.add(f.getAbsolutePath());
}
}
}
Here I have stored my images in my computer in "Libraries\Pictures\homepage" path. I wanted to get the images in gallery but I could not. I don know what causes this exception can anyone please tell the solution
try this..
File targetDir=getDir("Libraries\Pictures\homepage",Context.MODE_PRIVATE);
String targetPath=targetDir.toString();
From the exception, you have a null pointer on line 27, which means that the files object that you are iterating is null. You use the listFiles method to obtain that object, but the listFiles method can return null. You have to check whether you have null or not to avoid your app crashing. See example below. Also, refer to the File class documentation.
if (files == null) {
// handle case where the file object is not a directory
}
else {
for(File f : files){
myHorizontalLayout.add(f.getAbsolutePath());
}
}
I think you can't directly get images from your computer path.
You have to copy that images in your drawable or assests folder of the application.
Or your images should reside in either your device or emulator gallery or any other folders. But it should be in device or emulator in whichever you are testing.
See this line in tutorial you used.
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
So this is your device's sdcard path - external storage path.
Related
I downloaded a text file by a click button functionality, using Selenium Java.
then the file is downloaded to a particular location in the system, for example,
C://myAppfiles.
But I can't access that downloaded folder because of some reason. But I have to read that file while downloading.
How to do it? is it possible to read that file from the browser(chrome) using selenium or any other method is available?
so I'd suggest to do the following:
wait until file download is done completely.
After that- try to list all the files in the given directory:
all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
That will help You to understand if there any files at all (in the given directory).
Dont forget to make paths platform independent (to the folder/ file), like:
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"myDownloadedFile.txt");
Also, You might want to check whether file actually exists via Path methods.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
Path filePath= Paths.get("C:\\myAppfiles\\downloaded.txt");
System.out.println("if exists: " + Files.exists(firstPath));
}
}
Additionally, path suggests You to check some other options on the file:
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
Once You face any exception- feel free to post it here.
Hope this helps You
I'm using eclipse to created an RCP Application, and I'm not being able to load an image because I don't know how to find it in the generated code. I'm going to try to explain my particular issue.
Note: the project is a Game editor, and it is located here: http://chelder86.github.com/ArcadeTongame/
Firstly, this is the project structure:
The next code runs the RCP application correctly inside Eclipse, after changing the Working Workspace in the Eclipse Running Config.
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = "src/figures/Sound48.png";
// or String picturePath = "bin/figures/Sound48.png";
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
But it does not work when I create a Product and export it as an RCP Application. I mean, the RCP application works, but it does not load that image.
Note: build.properties has the image checked.
I tried different combinations like these with the same result: java.io.FileNotFoundException, when I run it in Eclipse:
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = getClass().getResource("Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("bin/figures/Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("figures/Sound48.png").getHost();
// or similars
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
How could I load it correctly?
Thanks for any help! :)
Carlos
Try creating a separate "figures" folder alongside "icons" folder. Put only the image files there, not .java files. Don't forget to add it to the class path and to build.properties. Then something like this should work:
InputStream in = getClass().getResourceAsStream("figures/Sound48.png");
Image image = new Image(Display.getDefault(), in);
i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()
I have search all over the web but could not find answer to this question:
I need to debug the functioning of an application that changes the SplashScreen based on the module you are accessing.
I do know that the code:
SplashScreen splash = SplashScreen.getSplashScreen();
Can be used to get the instance when you pass either:
Splash from command line: java -splash:path/image.gif ClassFile
Splash image in manifest: splashscreen-image: img/SplashNomina.gif
Still when I tried to run the application by passing the -splash value from VM args in Eclipse it did not work.
Is it actually possible as SplashScreen.getSplashScreen() is always NULL.
I have been trying passing without success:
-splash:image.gif
-Dsplash=image.gif
Right now I see lots of limitations in this Splash api, as it is always required to have a parameter being passed. I think it would be much more flexible to be able to just pass the parameter at runtime :(
Any help woult be really appreciated!
OK, this has bitten me too.
I built a runnable jar
with manifest entry
SplashScreen-Image: MyGraphic.jpg
and it works as it's supposed to.
From Eclipse, specifying the VM arg as
-splash:MyGraphic.jpg
no such luck
SplashScreen.getSplashScreen() returns null.
The reason for this is the brain-dead implementation of SplashScreen.getSplashScreen() in the JDK (at least 1.6). I think. It's kind of hard to tell without getting into what the native code is doing. But, here is this method from java.awt.SplashScreen. I'm not sure if it's called but studying it did provide me with the essential clue I needed to get this working in Eclipse:
public synchronized URL getImageURL() throws IllegalStateException {
checkVisible();
if (imageURL == null) {
try {
String fileName = _getImageFileName(splashPtr);
String jarName = _getImageJarName(splashPtr);
if (fileName != null) {
if (jarName != null) {
imageURL = new URL("jar:"+(new File(jarName).toURL().toString())+"!/"+fileName);
} else {
imageURL = new File(fileName).toURL();
}
}
}
catch(java.net.MalformedURLException e) {
// we'll just return null in this case
}
}
return imageURL;
}
Note that in the case of a file (i.e. command-line rather than jar launch) it's not doing a getResource() to get the URL but opening a file relative to the CWD. Since Eclipse run configurations default to running from the root of the project, the answer is to specify the path as a relative path and not to expect a classpath lookup.
Therefore, since I am building with maven, my image is located at src/main/resources/MyGraphic.jpg. Specifying this as the command line parameter: i.e.
-splash:src/main/resources/MyGraphic.jpg
allows it to work in Eclipse (or, I guess, any command line)
I'm not sure WHY this is, since the getImageURL method is NOT called by getSplashScreen() but it DOES work.
To me this is kind of brain-dead on the part of Sun/Oracle. They could have easily done a classpath lookup with something like
imageURL = getResource(filename) but they did not.
The short answer is that the Splash Screen command line syntax refers to a filename relative to the current working direrctory, not relative to the classpath.
I'm answering 3 years later but I had the same problem and I tried to resolve.
I found the solution, and I think it would be useful to everybody.
You have to create a launch configuration, specifying in the VM arguments the parameter -splash:image.gif. This parameter refers to the root directory of the project (not /bin or /src). So you have to put your image in the same level as /bin and /src (or you can specify a different path in the -splash option).
When you export the runnable JAR from 'export' specifying the launch configuration you created before, it says 'can't include VM arguments, you have to specify from command line' (and it doesn't include your image.gif in the root).
So if you want to have a runnable jar with your splash image, you can refer to another topic on stackoverflow which i'm not finding anymore. Someone answered that the best solution is FatJar. You can proceed as follows: export > other > fat jar exporter. Tick 'select manifest file', specifying a MANIFEST.MF containing 'SplashScreen-Image: splash.gif' (if you don't know how to create, deselect this checkbox, create a jar with the default one, modify the one created and include it). In the next page of the exportation, be sure to include your images in the jar with the 'add dir' button (it includes the content of the directory specified to the root directory of the project, so pay attention with the directory in the manifest).
It worked for me.
So if you want to run with eclipse, add the splash image to the root directory and specify -splash:image.gif in the VM arguments. If you want to export a JAR, the FatJar plugin worked for me as I specified.
I hope it helps :)
(sorry for my english, i'm not english :P)
Well guys, I decided yo go my independent way because the Splash class is too monolithic, so here I put my class:
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SplashWindow extends JFrame {
private static final long serialVersionUID = 9090438525613758648L;
private static SplashWindow instance;
private boolean paintCalled = false;
private Image image;
private SplashWindow(Image image) {
super();
this.image = image;
JLabel label = new JLabel();
label.setIcon(new ImageIcon(image));
this.add(label);
this.setUndecorated(true);
this.setAlwaysOnTop(true);
this.pack();
this.setLocationRelativeTo(null);
}
public static void splash(URL imageURL) {
if (imageURL != null) {
splash(Toolkit.getDefaultToolkit().createImage(imageURL));
}
}
public static void splash(Image image) {
if (instance == null && image != null) {
instance = new SplashWindow(image);
instance.setVisible(true);
if (!EventQueue.isDispatchThread() && Runtime.getRuntime().availableProcessors() == 1) {
synchronized (instance) {
while (!instance.paintCalled) {
try {
instance.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
if (!paintCalled) {
paintCalled = true;
synchronized (this) {
notifyAll();
}
}
}
public static void disposeSplash() {
instance.setVisible(false);
instance.dispose();
}
}
Hope it helps someone ;)
I know this is possible but I'm not really sure where to start. Has anyone been able to achieve this?
Thanks.
The DataXmlExporter class described in this article will export a SQL lite DB to an XML file.
http://www.screaming-penguin.com/node/7749
The full example is available in this SVN repo. The ManageData class invokes the export.
http://totsp.com/svn/repo/AndroidExamples/trunk/
You will need to create an application class that exposes the DB and referenced as the application name in the AndroidManifest.xml file. Then use that DB as the argument to the DataXmlExporter constructor.
Here's the application class I use. You should already have a class (probably not named DatabaseHelper) that extends SQLiteOpenHelper
package com.billybobbain.android.someapp;
import android.app.Application;
import android.util.Log;
public class MyApplication extends Application {
public static final String APP_NAME = "SomeApp";
private DatabaseHelper dataHelper;
#Override
public void onCreate() {
super.onCreate();
Log.d(APP_NAME, "APPLICATION onCreate");
this.dataHelper = new DatabaseHelper(this);
}
#Override
public void onTerminate() {
Log.d(APP_NAME, "APPLICATION onTerminate");
super.onTerminate();
}
public DatabaseHelper getDataHelper() {
return this.dataHelper;
}
public void setDataHelper(DatabaseHelper dataHelper) {
this.dataHelper = dataHelper;
}
}
Have a look at the source code here exporting-a-sqlite-database-to-an-xml-file-in-android
The only change I had to make (to stop a few Eclipse warnings) was to close a cursor in the exportData( ) method. To make the code more portable, I also passed the XML file and location as an argument rather then as a declared final field.
The code writes the XML file to the SD card. Now, #mmaitlen who listed the source code on his blog doesn't add in any features to test for the existence of an external storage unit. So that's left for you to do.
However, you can embed some simple code to test for the existence of a writeable memory card with the following snippet (untested):
sdOkToWrite = false;
String sdTest = Environment.getExternalStorageState();
if (sdTest.equals(Environment.MEDIA_MOUNTED)) {
sdOkToWrite = true;
} else {
// Here's where you can code what to do without the external storage
}
Testing for the external storage is useful if you have large files to create that may exceed internal capacity.
I found this very helpful:
http://www.phonesdevelopers.com/1788273/
Using it the following way to export it to the sd card:
File sd = Environment.getExternalStorageDirectory();
String path = sd + "/" + DB_NAME + ".xml";
DatabaseDump databaseDump = new DatabaseDump(mySQLiteOpenHelperObject.getReadableDatabase(), path);
databaseDump.exportData();
Of course don't forget:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>