Using OpenNLP with Android? - android

I would like to use OpenNLP in my Android project. I imported the JAR and I can use it in my project but when I need to load a TokenizerModel (for example) I do not see how to proceed.
Cheers.

Putting my .bin model files in the assets folder and call the using getAssets() is working pretty fine.

Here is an example (originally written on Stack Overflow Documentation):
Sentence Detection using openNLP using CLI and Java API
using CLI:
$ opennlp SentenceDetector ./en-sent.bin < ./input.txt > output.txt
using API:
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.Objects;
public class FileUtils {
/**
* Get file data as string
*
* #param fileName
* #return
*/
public static String getFileDataAsString(String fileName) {
Objects.nonNull(fileName);
try {
String data = new String(readAllBytes(get(fileName)));
return data;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
}
class sentecedetectorutil:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectorUtil {
private SentenceModel model = null;
SentenceDetectorME sentenceDetector = null;
public SentenceDetectorUtil(String modelFile) {
Objects.nonNull(modelFile);
initSentenceModel(modelFile);
initSentenceDetectorME();
}
private void initSentenceDetectorME() {
sentenceDetector = new SentenceDetectorME(model);
}
private SentenceModel initSentenceModel(String file) {
InputStream modelIn;
try {
modelIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return null;
}
try {
model = new SentenceModel(modelIn);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
return model;
}
public String[] getSentencesFromFile(String inputFile) {
String data = FileUtils.getFileDataAsString(inputFile);
return sentenceDetector.sentDetect(data);
}
public String[] getSentences(String data) {
return sentenceDetector.sentDetect(data);
}
}
}
main class:
public class Main {
public static void main(String args[]) {
SentenceDetectorUtil util = new SentenceDetectorUtil(
"path//to//your//en-sent.bin");
String data = "Welcome to Stackoverflow Documentation.This is the first example in OenNLP.";
String[] sentences = util.getSentences(data);
for (String s : sentences)
System.out.println(s +"\n");
}
}
output will be:
Welcome to Stackoverflow Documentation.
This is the first example in OpenNLP.
And you can find some basic stuff here
lot of examples are covered in the above examples. that must do the work for you.

Related

ACRA 4.9.0 : How can I write ACRA report to file (in Application data folder)

I want to write the crash report in text file using latest Acra 4.9.0.
I can,t example for this latest version.
I tried using available documentation.
Acra is enabled
but it,s not writing in the file.
myApp
package com.myApp;
import org.acra.ACRA;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import com.myApp.Application.AppLauncher;
import com.myApp.interfaces.AppEvents;
import com.myApp.R;
import com.utils.Config;
import com.utils.Constants;
import com.utils.DeviceValidator;
public class myApp extends FragmentActivity
{
private AppLauncher appLauncher = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(!ACRA.isACRASenderServiceProcess())
{
setContentView(R.layout.activity_myApp);
appLauncher = new AppLauncher();
appLauncher.registerEventListener(appEventsListener);
appLauncher.initApp(this);
}
}
#Override
public void onPause() {
super.onPause();
if(!DeviceValidator.isDeviceValid())
{
return;
}
appLauncher.activityOnPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
appLauncher.activityOnResume();
}
}
AcraApplication
package com.myAPP;
import org.acra.ACRA;
import org.acra.ReportField;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.sender.HttpSender.Method;
import android.app.Application;
#ReportsCrashes(
formUri = "http://staging.jemtv.com/variable_dump/index.php",
customReportContent = { ReportField.REPORT_ID, ReportField.DEVICE_ID, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.STACK_TRACE, ReportField.CUSTOM_DATA, ReportField.LOGCAT },
httpMethod = Method.POST,
reportSenderFactoryClasses = org.acra.util.MyOwnSenderFactory.class,
mode = ReportingInteractionMode.SILENT
)
public class AcraApplication extends Application
{
public AcraApplication()
{
super();
}
#Override
public void onCreate() {
super.onCreate();
ACRA.init(this);
}
}
MyOwnSender
package org.acra.util;
import java.io.File;
import java.io.FileOutputStream;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
public class MyOwnSender implements ReportSender {
private static final String FILE_NAME = "AcraReport.txt";
//private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>();
//private FileWriter crashReport = null;
MyOwnSender(Context context, #NonNull ACRAConfiguration config)
{
Log.d("testAcra", "MyOwnSender created");
/* File logFile = new File(context.getFilesDir().getPath() + "/" + FILE_NAME, FILE_NAME);
try {
crashReport = new FileWriter(logFile, true);
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public void send(Context context, CrashReportData report) throws ReportSenderException
{
// Iterate over the CrashReportData instance and do whatever
// you need with each pair of ReportField key / String value
String finalReport = createCrashReport(report);
String tempFile = context.getFilesDir().getPath() + "/" + FILE_NAME;
try
{
File detailedFile = new File(tempFile);
if(!detailedFile.exists())
detailedFile.createNewFile();
FileOutputStream stream = new FileOutputStream(detailedFile, true);
stream.write(finalReport.getBytes());
Log.d("testAcra","adding to file: "+stream);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/*final Map<String, String> finalReport = remap(report);
try {
BufferedWriter buf = new BufferedWriter(crashReport);
Set<Entry<String, String>> set = reportBody.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
while (i.hasNext()) {
Map.Entry<String, String> me = (Entry<String, String>) i.next();
buf.append("[" + me.getKey() + "]=" + me.getValue());
}
buf.flush();
buf.close();
} catch (IOException e) {
Log.e("TAG", "IO ERROR", e);
}*/
}
private String createCrashReport(CrashReportData crashReportData){
StringBuilder body = new StringBuilder();
body.append("ReportID : " + crashReportData.getProperty(ReportField.REPORT_ID))
.append("\n")
.append("DeviceID : " + crashReportData.getProperty(ReportField.DEVICE_ID))
.append("\n")
.append("AppVersionName : " + crashReportData.getProperty(ReportField.APP_VERSION_NAME))
.append("\n")
.append("Android Version : " + crashReportData.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("CustomData : " + crashReportData.getProperty(ReportField.CUSTOM_DATA))
.append("\n")
.append("STACK TRACE : \n" + crashReportData.getProperty(ReportField.STACK_TRACE))
.append("\n")
.append("LogCAT : \n" + crashReportData.getProperty(ReportField.LOGCAT));
return body.toString();
}
/* private Map<String, String> remap(Map<ReportField, String> report) {
Set<ReportField>fields = ACRA.getConfig().getReportFields();
final Map<String, String> finalReport = new HashMap<String, String>(report.size());
for (ReportField field : fields)
{
if (mMapping == null || mMapping.get(field) == null)
finalReport.put(field.toString(), report.get(field));
else
finalReport.put(mMapping.get(field), report.get(field));
}
return finalReport;
}*/
}
MyOwnSenderFactory
package org.acra.util;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderFactory;
import android.content.Context;
import android.support.annotation.NonNull;
public class MyOwnSenderFactory implements ReportSenderFactory {
// NB requires a no arg constructor.
/*MyOwnSenderFactory()
{
Log.e("testAcra", "MyOwnSenderFactory created");
}*/
#Override
#NonNull
public ReportSender create(#NonNull Context context, #NonNull ACRAConfiguration config) {
// TODO Auto-generated method stub
return new MyOwnSender(context, config);
}
}
Because i was using jar file instead of aar
in my manifest i was missing
<service
android:name="org.acra.sender.SenderService"
android:exported="false"
android:process=":acra" />
enter code here
That,s why SendeService used in Acra was not starting.
I want to write in application data folder
That is called internal data
I have created my own saver class to handle all of those savings:
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Saver {
static FileOutputStream fos;
static FileInputStream fis;
public static void save(String filename, String data, Context c){
try {
fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String file;
public String getFile(){return file;}
public void setFile(String loc){
file = loc;
}
String result;
private static String mainLoad(String fn, Context c){
String collected = null;
try{
fis = c.openFileInput(fn);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
fis.close();
return collected;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public static int loadInt(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Integer.parseInt(mainLoad(fn,c));
}
public static double loadDouble(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Double.parseDouble(mainLoad(fn,c));
}
public static float loadFloat(String fn, Context c){
return Float.parseFloat(mainLoad(fn,c));
}
public static String loadString(String fn, Context c){
return mainLoad(fn, c);
}
public static Boolean loadBoolean(String fn, Context c){
if(mainLoad(fn,c) == null) return false;
else return Boolean.parseBoolean(mainLoad(fn,c));
}
public static BigInteger loadBigInteger(String fn, Context c){
return new BigInteger(mainLoad(fn,c));
}
public static BigDecimal loadBigDecimal(String fn, Context c){
return new BigDecimal(mainLoad(fn,c));
}
}
I want to write the crash report in text file using latest Acra 4.9.0. I can,t example for this latest version.
If you want to write to a .txt file on server, try this backend. Uses the default sender:
<?php
// Outputs all POST parameters to a text file. The file name is the date_time of the report reception
$fileName = date('Y-m-d_H-i-s').'.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fclose($file);
?>
If you only want to write locally, then the point of ACRA disappears as you cannot get the files.
If you create .txt files to transmit them, it is actually better to use the backend I linked. It transmits the raw data, and you can get all your fields in a .txt file

Where to put resources in Android for ResourceBundle.getBundle(String path)?

I'm using one of ee-jars in my android project. It uses ResourceBundle.getBundle(String path) for i18n. Since resources are stripped in jar and .apk does not contain resources and i'm getting an exception:
java.util.MissingResourceException: Can't find resource for bundle 'org/apache/xml/security/resource/xmlsecurity_en_US', key ''
at java.util.ResourceBundle.missingResourceException(ResourceBundle.java:239)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:231)
at org.apache.wss4j.common.crypto.WSS4JResourceBundle.<init>(WSS4JResourceBundle.java:54)
at org.apache.wss4j.common.crypto.WSProviderConfig.initializeResourceBundles(WSProviderConfig.java:199)
at org.apache.wss4j.common.crypto.WSProviderConfig.init(WSProviderConfig.java:65)
at org.apache.wss4j.dom.WSSConfig.init(WSSConfig.java:428)
at org.apache.wss4j.dom.WSSConfig.getNewInstance(WSSConfig.java:435)
at org.apache.wss4j.dom.WSSecurityEngine.getWssConfig(WSSecurityEngine.java:148)
at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:215)
at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:190)
at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:96)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:243)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:261)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:70)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1088)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1024)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:982)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1043)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:841)
What can i do in order to fix it? My idea is to get resources from jar and put them into resources folder in Android project. Where is the correct place for it? Android does support ResourceBundle.getBundle(String path) (reference) but it's not written where to put the resources.
I had to:
introduce resource loader interface (WSS4JResourceBundle.ResourceBundleLoader)
introduce static resource loader variable to load resources (public static ResourceBundleLoader sharedLoader)
replace loading resource using ResourceBundle.getBundle to static var method invocation (wss4jSecResourceBundle = sharedLoader.getBundle("messages.wss4j_errors"); f.e.)
create default (DefaultResourceBundleLoader) and android implementation (AndroidResourceBundleLoader)
repackage resources to android's project assets folder
inject android impl instead of default one on app launch (WSS4JResourceBundle.sharedLoader = new AndroidResourceBundleLoader(ctx, "wss4j/");)
modified WSS4JResourceBundle:
package org.apache.wss4j.common.crypto;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.I18n;
/**
* ResourceBundle for WSS4J
*/
public class WSS4JResourceBundle extends ResourceBundle {
/**
* Loader API
*/
public interface ResourceBundleLoader {
ResourceBundle getBundle(String path);
ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader);
}
// default
public static ResourceBundleLoader sharedLoader = new DefaultResourceBundleLoader();
/**
* Default IMPL
*/
public static class DefaultResourceBundleLoader implements ResourceBundleLoader {
#Override
public ResourceBundle getBundle(String path) {
return ResourceBundle.getBundle(path);
}
#Override
public ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) {
return ResourceBundle.getBundle(baseName, locale, loader);
}
}
private static final org.slf4j.Logger LOG =
org.slf4j.LoggerFactory.getLogger(WSS4JResourceBundle.class);
private final ResourceBundle wss4jSecResourceBundle;
private final ResourceBundle xmlSecResourceBundle;
public WSS4JResourceBundle() {
wss4jSecResourceBundle = sharedLoader.getBundle("messages.wss4j_errors");
ResourceBundle tmpResourceBundle;
try {
tmpResourceBundle = sharedLoader.getBundle(
Constants.exceptionMessagesResourceBundleBase,
Locale.getDefault(),
I18n.class.getClassLoader());
} catch (MissingResourceException ex) {
// Using a Locale of which there is no properties file.
LOG.debug(ex.getMessage());
// Default to en/US
tmpResourceBundle =
sharedLoader.getBundle(Constants.exceptionMessagesResourceBundleBase,
new Locale("en", "US"), I18n.class.getClassLoader());
}
xmlSecResourceBundle = tmpResourceBundle;
}
#Override
protected Object handleGetObject(String key) {
Object value = null;
try {
value = wss4jSecResourceBundle.getObject(key);
} catch (MissingResourceException e) {
try {
value = xmlSecResourceBundle.getObject(key);
} catch (MissingResourceException ex) { //NOPMD
//ignore
}
}
return value;
}
#Override
public Enumeration<String> getKeys() {
throw new UnsupportedOperationException("getKeys not supported");
}
}
new AndroidResourceBundleLoader:
package org.apache.wss4j.common.crypto;
import android.content.Context;
import android.content.res.AssetManager;
import com.splinex.streaming.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class AndroidResourceBundleLoader implements WSS4JResourceBundle.ResourceBundleLoader {
private static final String TAG = AndroidResourceBundleLoader.class.getSimpleName();
private String prefix;
private AssetManager manager;
public AndroidResourceBundleLoader(Context context, String prefix) {
manager = context.getAssets();
this.prefix = prefix;
}
#Override
public ResourceBundle getBundle(String path) {
try {
String fullPath = prefix + path.replace(".", "/") + ".properties";
return new PropertyResourceBundle(manager.open(fullPath));
} catch (IOException e) {
android.util.Log.e(TAG, "Failed to load " + path, e);
throw new RuntimeException(e);
}
}
#Override
public ResourceBundle getBundle(String path, Locale locale, ClassLoader classLoader) {
return getBundle(path + "_" + locale.getLanguage());
}
}
Inject android impl like this:
WSS4JResourceBundle.sharedLoader = new AndroidResourceBundleLoader(ctx, "wss4j/");

convert csv format to Json in android

Example to convert csv format to Json in android. I found a solution in Converting an CSV file to a JSON object in Java but not working or I am missing anything.
Thanks in advance.
package com.example.readfilefromsdcard;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnWriteSDFile;
Button btnReadSDFile;
String path = "/sdcard/mydocs/test.csv";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
ConvertCsvToJson(path,"TestJavaBeans");
// ConvertCsvToJson1(path);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void ConvertCsvToJson(String path, String clsName) throws IOException, ClassNotFoundException {
String pathToCsvFile = path;
String javaBeanClassName = "" + clsName;
final File file = new File(pathToCsvFile);
if (!file.exists()) {
System.out.println("The file you specified does not exist. path=" + pathToCsvFile);
}
Class<?> type = null;
try {
type = Class.forName(javaBeanClassName);
} catch (ClassNotFoundException e) {
System.out.println("The java bean you specified does not exist. className=" + javaBeanClassName);
}
HeaderColumnNameMappingStrategy<TestJavaBeans> strat = new HeaderColumnNameMappingStrategy<TestJavaBeans>();
//strat.setType(type);
CsvToBean<TestJavaBeans> csv = new CsvToBean<TestJavaBeans>();
List<TestJavaBeans> list = csv.parse(strat, new InputStreamReader(new FileInputStream(file)));
System.out.println(new ObjectMapper().writeValueAsString(list));
}
public void ConvertCsvToJson1(String path) throws IOException, ClassNotFoundException {
final ColumnPositionMappingStrategy<TestJavaBeans > strategy = new ColumnPositionMappingStrategy<TestJavaBeans>();
strategy.setType(TestJavaBeans .class);
strategy.setColumnMapping(new String[] { "name", "id", });
final CsvToBean<TestJavaBeans > csvToBean = new CsvToBean<TestJavaBeans >();
final List<TestJavaBeans > beanExamples;
try {
final Reader reader = new FileReader(path);
beanExamples = csvToBean.parse(strategy, reader);
System.out.println(new ObjectMapper().writeValueAsString(beanExamples));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
package com.example.readfilefromsdcard;
public class TestJavaBeans {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Referenced libraries : jackson-all-1.9.0.jar and opencsv-3.3.jar
log: Could not find method java.beans.Introspector.getBeanInfo, referenced from method com.opencsv.bean.HeaderColumnNameMappingStrategy.loadDescriptors
There's really no universal "convert": JSON is a heirarchical structure, while CSV is flat. You need to model the JSON object and map fields from the CSV to the JSON object one at a time. It's more a logic problem rather than a coding one.
I would suggest this approach
create a Java "wrapper" class that has a class variable List<TestJavaBeans> list
Then use Jackson to convert this "wrapper" to json
The link which i preferred for converting csv to json is as follows:
https://github.com/cparker15/csv-to-json?files=1

Can't read local json file : open failed:ENOENT (No such file or directory)

I'm developping and android application in which i wan't to read a local json file to populate a ListView, the problem is that i can't read the local json file, and here how i proceed.
First i created an object class because i want to work with ObjectMapper.
already created the base classes (Theme, CouchesTheme and ClassesEvenement).
here's the subclasse LireTheme:
package com.myapp.theme;
public class LireTheme {
private Theme theme;
private CouchesTheme couchesTheme;
private ClassesEvenement classesEvenement;
private String message;
private boolean ok;
public LireTheme() {
super();
// TODO Auto-generated constructor stub
}
public LireTheme(Theme theme, CouchesTheme couchesTheme,
ClassesEvenement classesEvenement, String message, boolean ok) {
super();
this.theme = theme;
this.couchesTheme = couchesTheme;
this.classesEvenement = classesEvenement;
this.message = message;
this.ok = ok;
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
}
public CouchesTheme getCouchesTheme() {
return couchesTheme;
}
public void setCouchesTheme(CouchesTheme couchesTheme) {
this.couchesTheme = couchesTheme;
}
public ClassesEvenement getClassesEvenement() {
return classesEvenement;
}
public void setClassesEvenement(ClassesEvenement classesEvenement) {
this.classesEvenement = classesEvenement;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isOk() {
return ok;
}
public void setOk(boolean ok) {
this.ok = ok;
}
}
second i created a correspondence HashMap class of Theme list.
package com.myapp.recensement;
import java.util.ArrayList;
import java.util.HashMap;
import com.myapp.theme.LireTheme;
public class LireThemes extends HashMap<String, ArrayList<LireTheme>> {
private static final long serialVersionUID = 1L;
}
and then use it like this.
package com.myapp.recensement;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import android.os.Environment;
import android.util.Log;
import com.myapp.theme.LireTheme;
public class LireThemesController {
private ObjectMapper objectMapper = null;
private JsonFactory jsonFactory = null;
private JsonParser jp = null;
private ArrayList<LireTheme> themeList = null;
private LireThemes lirethemes = null;
private File jsonFile;
boolean availble=false;
public LireThemesController() {
objectMapper = new ObjectMapper();
jsonFactory = new JsonFactory();
}
public void init() {
availble=isExternalStorageReadble();
if(availble){
Log.w("myApp", "file available");
}else{
Log.w("myApp", "file not available");
}
jsonFile = new File("c:\\lireThemes.json");
try{
jp = jsonFactory.createJsonParser(jsonFile);
lirethemes = objectMapper.readValue(jp, LireThemes.class);
themeList = lirethemes.get("themes");
} catch(JsonParseException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
public ArrayList<LireTheme> findAll() {
return themeList;
}
public LireTheme findById(int id) {
return themeList.get(id);
}
public boolean isExternalStorageReadble() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
}
and also already added the permission in the AndroidManifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
when i run i get this error :
12-29 04:16:04.287: W/System.err(2060): java.io.FileNotFoundException: /c:\lireThemes.json: open failed: ENOENT (No such file or directory).
any solution for that problem please ?
You cannot read a file on your Android device from c:\, which is a Windows File System path.
You have to copy your JSON file inside the Assets folder and then load it using
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
The Problem is jsonFile = new File("c:\\lireThemes.json");
There is no c:\lireThemes.json file on your android device.
If you add the file to your assets directory (in your project) you can access by getAssets().open("lireThemes.json") which will return an input stream
or you can put it in your res/raw folder and access it by getActivity().getResources().openRawResource(R.raw.lireThemes) which will also return an input stream

Minitemplator on android, how to access to template file in asset directory?

I am trying to integrate Minitemplator (http://www.source-code.biz/MiniTemplator/) to an application of android but i am little lost.
I can access to the template file, the template file is in asset directory and i try to get the file at this way:
Uri path = Uri.parse("file:///android_asset/index.html");
and instantiate the object at this way:
MiniTemplator t = new MiniTemplator(path.getPath());
but it send me an io exception that file or folder doesn't exists.
how is the correct way to send the file to instantiate my minitemplator object?
This is the complete code:
package com.kentverger.minitemplator;
import java.io.File;
import java.io.IOException;
import biz.source_code.miniTemplator.MiniTemplator;
import biz.source_code.miniTemplator.MiniTemplator.TemplateSyntaxException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
public class Template extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
WebView index = (WebView) findViewById(R.id.indexWebView);
Uri path = Uri.parse("file:///android_asset/index.html");
try {
MiniTemplator t = new MiniTemplator(path.getPath());
t.setVariable("titulo", "Hola mundo generado desde java");
String html_code = t.generateOutput();
index.loadData(html_code, "text/html", null);
} catch (TemplateSyntaxException e) {
Log.d("ERROR 1", e.getMessage());
} catch (IOException e) {
Log.d("ERROR 2", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_template, menu);
return true;
}
}
I solve my problem loading the template from a string instead a html file.
First I have to create a specification object that will content the template String
MiniTemplator.TemplateSpecification templateSpec = new MiniTemplator.TemplateSpecification();
Then add the template String to templateString property
templateSpec.templateText = "<html><body><h1>${hello}</h1></body></html>";
Next we have to instantiate the Minitemplator object with the speciciations object
t = new MiniTemplator(templateSpec);
And we already to change the values of the variables in the template like this:
t.setVariable("hello", "Hola Mundo!");
Thanks a lot :)
MiniTemplator miniTemplator = openHtmlFileFromAssert(activity, "test.html");
Try this method is working and is help to read html file from assert folder
public MiniTemplator openHtmlFileFromAssert(Activity activity, String fileName) {
try {
AssetManager assetManager = activity.getAssets();
InputStream inputStream = assetManager.open(fileName);
MiniTemplator.Builder templateBuilder = new MiniTemplator.Builder();
return templateBuilder.build(inputStream, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Categories

Resources