In the book Beginning Android 4 games development by Mario Zechner and Robert Green I am following along to start making a game of my own. We create a framework for the game first and then implement it into one class, and I got one error which I could not figure out. The error occured when I tried to instantiate something from a class called AndroidFileIO.
This is how the book describes how to instantiate it:
FileIO fileIO
fileIO = new AndroidFileIO(getAssets());
and the class it gets it from is:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Environment;
import android.preference.PreferenceManager;
import com.example.android4gamedevtut.FileIO;
public class AndroidFileIO implements FileIO{
Context context;
AssetManager assets;
String externalStoragePath;
public AndroidFileIO(Context assetManager) {
this.context = assetManager;
this.assets = assetManager.getAssets();
this.externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator;
}
#Override
public InputStream readAsset(String fileName) throws IOException {
return assets.open(fileName);
}
#Override
public InputStream readFile(String fileName) throws IOException {
return new FileInputStream(externalStoragePath + fileName);
}
#Override
public OutputStream writeFile(String fileName) throws IOException {
return new FileOutputStream(externalStoragePath + fileName);
}
public SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
The error that is stopping me is saying "The constructor AndroidFileIO(AssetManager) is undefined" and eclipses suggests too fixes to the problem. The first being to "change the constructor AndroidFileIO(Context) to AndroidFileIO(AssetManager)" and the second being "create a constructor AndroidFileIO(AssetManager)". Please answer this question in simple terms I am very new to java.
you should use
fileIO = new AndroidFileIO(this);
instead of getAsset();
refer to line 54 in https://code.google.com/p/beginning-android-games-2/source/browse/trunk/ch09-jumper/src/com/badlogic/androidgames/framework/impl/GLGame.java?r=4
Related
When I am importing the HTML File according to the tutorialpoint link https://www.tutorialspoint.com/jsoup/jsoup_load_file.htm
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class jsoupTester {
public static void main(String[] args) throws IOException, URISyntaxException {
URL path = ClassLoader.getSystemResource("test.htm");
File input = new File(path.toURI());
Document document = Jsoup.parse(input, "UTF-8", "");
System.out.println(document.title());
}
}
I got this error when I run the program:
Exception in thread "main" java.lang.NullPointerException
at jsoupTester.main(jsoupTester.java:13)
Note: jsoupTester.java file and temp.htm are in the same location
May I know how to solve this issue? Your suggestions will be highly appreciated :)
Have you checked the website properly? the code documentation showed this
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsoupTester {
public static void main(String[] args) throws IOException, URISyntaxException {
URL path = ClassLoader.getSystemResource("test.htm");
File input = new File(path.toURI());
Document document = Jsoup.parse(input, "UTF-8"); // Only 2 parameters
System.out.println(document.title());
}
}
Error
Document document = Jsoup.parse(input, "UTF-8", ""); // 3rd parameter is not included in the documentation
As you can see the error is that you have another redundant parameter which I believe is causing the error. Remove that "" in your code and it will work fine. Hope that answers your question :)
How to call screenshot method from one class to other class?
How to take screenshot home page after logging in to my code?
Below are the classes:-
Properties class:
package basepackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.io.FileHandler;
public class PropertiesClass extends BaseClass {
public static String propfile(String username) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\config.prop");
prop.load(fis);
return prop.getProperty(username);
}
public static void loginscreenshot() throws Exception {
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(file, new File("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\Screenshots.png"));
}
LoginPageClass:
package com.org.swag.Page;
import org.openqa.selenium.support.PageFactory;
import com.org.swag.pageobject.LoginPageObjects;
import basepackage.BaseClass;
import basepackage.PropertiesClass;
public class LoginPage extends BaseClass {
public void loginpage() throws Exception {
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
lpo.menu.click();
lpo.logout.click();
}
}
Simply call the static screenshot method from another class (which imports basepackage.PropertiesClass) at the desired step. In your code, add the call after logging in:
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
PropertiesClass.loginscreenshot();
lpo.menu.click();
lpo.logout.click();
I'm trying to mock an external library, however the actual object created in APKDecompiler is being used, instead of the mock object.
Test code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import APKDecompiler;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.*;
import java.io.File;
import java.io.IOException;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Dex2jar.class})
public class TestAPKDecompiler {
//As this only uses external libraries, I will only test that they are called correctly by mocking them.
#Test
public void testAPKDecompiler() {
try {
File testFile = new File("ApkExtractor/src/test/resources/testApp.jar");
String expectedDirectory = testFile.getAbsolutePath().substring(0, testFile.getAbsolutePath().length() - 4);
mockStatic(Dex2jar.class);
Dex2jar mockApkToProcess = createMock(Dex2jar.class);
Decompiler mockDecompiler = createNiceMockAndExpectNew(Decompiler.class);
expect(Dex2jar.from(testFile)).andStubReturn(mockApkToProcess);
mockApkToProcess.to(new File(expectedDirectory + ".jar"));
expectLastCall();
PowerMock.expectNew(Decompiler.class).andReturn(mockDecompiler).anyTimes();
expect(mockDecompiler.decompileToDir(expectedDirectory + ".jar", expectedDirectory)).andReturn(0);
replay(mockApkToProcess);
PowerMock.replay(mockDecompiler);
replayAll();
String actualDirectory = APKDecompiler.decompileAPKToDirectory(testFile);
verify(mockApkToProcess);
verify(mockDecompiler);
verifyAll();
assertEquals(expectedDirectory, actualDirectory);
testFile.delete();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Class code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import jd.core.DecompilerException;
import java.io.File;
import java.io.IOException;
public class APKDecompiler {
public static String decompileAPKToDirectory(File filename) throws IOException, DecompilerException {
String filenameWithoutFileExtension = filename.getAbsolutePath().substring(0, filename.getAbsolutePath().length() - 4);
Dex2jar apkToProcess = Dex2jar.from(filename);
File jar = new File(filenameWithoutFileExtension + ".jar");
apkToProcess.to(jar);
Decompiler decompiler = new Decompiler();
decompiler.decompileToDir(filenameWithoutFileExtension + ".jar", filenameWithoutFileExtension);
return filenameWithoutFileExtension;
}
I've tried this and I haven't had any luck. EasyMock: Mocked object is calling actual method
I get a FileNotFoundException when decompiler.decompileToDir is called, which shouldn't happen as I should be mocking the class.
Any help would be greatly appreciated.
The answer was I didn't include the class i was testing in the #PrepareForTest annotation.
#PrepareForTest({APKDecompiler.class, Dex2jar.class, Decompiler.class})
I tried to run an android project in Cordova with self-build plugin,
Heres the code in JS and java for the plugin
var cordova = require('cordova');
var Carrier = function() {};
Carrier.prototype.getCarrierCode = function(success, error) {
cordova.exec(success, error, 'CarrierPlugin', 'getCarrierCode', []);
};
var carrier = new Carrier();
module.exports = carrier;
this is the java code:
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.content.ContentResolver;
public class CarrierPlugin extends CordovaPlugin{
public static final String TAG = "CarrierPlugin";
public static final String ACTION_GET_CARRIER_CODE = "getCarrierCode";
//public TelephonyManager tm;
#Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
// TODO Auto-generated method stub
super.initialize(cordova, webView);
}
#Override
public boolean execute(String action, CordovaArgs args,
CallbackContext callbackContext) throws JSONException{
callbackContext.success("run it");
return true;
}
}
the error I got is "cannot find symbol :"
the strange thing is that, even if I change the code in the CarrierPlugin.java(delete the JSONException in line 16), it reported the same error.
My Eclipse says, you should import CordovaInterface, CordovaWebView and CordovaArgs.
And you might be missing package declaration as well, depending wherever you want to put your plugin's java files, such as:
package com.yourdomain.etc in the very first line of your Java file.
Below is my code, I'm not understanding the cause of the "ECHONEST api 4 NULL pointer exception":
package com.main;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.echonest.api.v4.EchoNestAPI;
import com.echonest.api.v4.EchoNestException;
import com.echonest.api.v4.Track;
import com.echonest.api.v4.TrackAnalysis;
public class SongAnalysis {
private static final String API_KEY = "14CPBOK0IFN0HRC0R";
public String getTempo(String fileName){
return null;
}
public static void main (String [] args)throws EchoNestException, IOException{
EchoNestAPI echoNest = new EchoNestAPI(API_KEY);
File file = new File("C:\\Users\\wooh\\workspace\\SongAnalysis\\songs\\b.mp3");
Track track = echoNest.uploadTrack(file,false );
track.waitForAnalysis(30000);
TrackAnalysis a = track.getAnalysis();
System.out.println("Tempo" + a.getTempo());
}
}
The likely occurrences of your NPE are:
echoNest is null.
track is null.
a is null.
You would want to pinpoint the specific location that your NullPointerException occurs, then ensure that when you instantiate the object, the object you need is being returned.