how to get browser history in android? - android

I would like to implement an application to get android default browser history and saving the browser history to an xml file.But the browser history is not saving in some devices into an xml file.
I have implemented my application for get the browser history info to save to xml file as follows:
private void browserHistoryDOM() {
try{
File newxmlfile = new File("/sdcard/Xmlfiles/briwserHistory.xml");
newxmlfile.createNewFile();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("root");
document.appendChild(rootElement);
Cursor mCur = managedQuery(Browser.BOOKMARKS_URI,Browser.HISTORY_PROJECTION, null, null, null);
mCur.moveToFirst();
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
Element em = document.createElement("bookmarkIdx");
em.appendChild(document.createTextNode(mCur.getString(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX)));
rootElement.appendChild(em);
long callDate = Long.parseLong(mCur.getString(Browser.HISTORY_PROJECTION_DATE_INDEX));
SimpleDateFormat datePattern = new SimpleDateFormat ("dd-MM-yyyy/h:m:s:a");
datePattern.setTimeZone(TimeZone.getTimeZone("GMT"));
String date_str = datePattern.format(new Date(callDate));
Element em1 = document.createElement("dateIdx");
em1.appendChild(document.createTextNode(date_str));
rootElement.appendChild(em1);
Element em2 = document.createElement("idIdx");
em2.appendChild(document.createTextNode(mCur.getString(Browser.HISTORY_PROJECTION_ID_INDEX)));
rootElement.appendChild(em2);
Element em3 = document.createElement("titleIdx");
em3.appendChild(document.createTextNode(mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX)));
rootElement.appendChild(em3);
Element em4 = document.createElement("urlIdx");
em4.appendChild(document.createTextNode(mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX)));
rootElement.appendChild(em4);
Element em5 = document.createElement("visitsIdx");
em5.appendChild(document.createTextNode(mCur.getString(Browser.HISTORY_PROJECTION_VISITS_INDEX)));
rootElement.appendChild(em5);
long searchDate = Long.parseLong(mCur.getString(Browser.SEARCHES_PROJECTION_DATE_INDEX));
SimpleDateFormat datePattern1 = new SimpleDateFormat ("dd-MM-yyyy/h:m:s:a");
datePattern1.setTimeZone(TimeZone.getTimeZone("GMT"));
String date_str1 = datePattern.format(new Date(searchDate));
Element em6 = document.createElement("searchDateIdx");
em6.appendChild(document.createTextNode(date_str1));
rootElement.appendChild(em6);
Element em7 = document.createElement("searchIdx");
em7.appendChild(document.createTextNode(mCur.getString(Browser.SEARCHES_PROJECTION_SEARCH_INDEX)));
rootElement.appendChild(em7);
Element em8 = document.createElement("truncateIdIdx");
em8.appendChild(document.createTextNode(mCur.getString(Browser.TRUNCATE_HISTORY_PROJECTION_ID_INDEX)));
rootElement.appendChild(em8);
Element em9 = document.createElement("truncateOldest");
em9.appendChild(document.createTextNode(mCur.getString(Browser.TRUNCATE_N_OLDEST)));
rootElement.appendChild(em9);
mCur.moveToNext();
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(newxmlfile);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
By using the above method i can get the browser history and able to save the data into xml file on sdcard.But in some kind of android devices are not getting browser history completly and not saving into xml file.If I test the app on Motorola Droid device then it is working fine.But If I test the same app on I have tested app on npm702 NOVO7PALADIN then i am not able to get browser history in my xml file.

First, never hardwire /sdcard. Use Environment.getExternalStorageDirectory() to get to the root of external storage.
Second, Browser.BOOKMARKS_URI will, at most, work for the open source Browser app that is part of the Android Open Source Project. Device manufacturers are welcome to replace that app with something else that will not be recording its history, bookmarks, or anything else in that ContentProvider. Similarly, users are allowed to download third-party browsers, which may not be storing things in that ContentProvider.
Third, NOVO7PALADIN may not have passed the Compatibility Test Suite, particularly if it does not have the Google Play Store (formerly Android Market) pre-installed. That would mean that the device manufacturer is welcome to break anything they want, including whether the open source Browser app stores things in that ContentProvider.
You would need to contact the NOVO7PALADIN manufacturer to learn anything more.

Related

JSF download file on android device returns .htm file

I'm currently facing a problem when use JSF download file on mobile.
Everything works fine as long as I use my desktop browser, but as soon as I change to my mobile device,I get a .html file which contains the source code.
Here is my download method
public StreamedContent getDrawing() throws Exception {
DocumentFile documentFile = (DocumentFile) getViewScope("documentFile");
if (documentFile != null) {
byte[] content = documentFileService.download(documentFile.getId());
InputStream stream = new ByteArrayInputStream(content);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.setResponseContentLength(content.length);
StreamedContent content2 = new DefaultStreamedContent(stream,
URLEncoder.encode(documentFile.getFilename(), "UTF-8"));
facesContext.responseComplete();
return content2;
}
return null;
}
This is my downloadButton
<h:commandButton value="fileDownload">
<p:fileDownload value="#{controller.drawing}"
contentDisposition="attachment"></p:fileDownload>
<f:ajax disabled="true" />
</h:commandButton>
I had saw this same issue,but it can not solve my problem
Now I don't know how to solve this problem

Ediiting xml node value in my xml file in res/raw folder(Android)

I am new to Android. I have been trying to update a node value of my xml file using DomParser. I have been workin with asset folder xml file to read. I realised asset folder files cannot be updated and then created a raw folder to save my xml file.I have been refering many answers provided by different people for a long time but nothing is workin!
Portion of my .xml file
<events>
<type>ABC</type>
<time>1:30-2:45pm</time>
<day>XYX</day>
<note>123</note>
</events>
and I have been trying the code
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
InputStream is = this.getResources().openRawResource(temp1);
Document doc = docBuilder.parse(is);
if (null != doc.getDocumentElement()){
v1.setText("\n\nhiii888",doc.getDocumentElement()); ("HERE")
RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
layout.addView(v1);
}
Node nodes = doc.getElementsByTagName("events").item(0);
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
if("type".equals(nodes.getNodeName())){
node.setNodeValue("ABC123");
}
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("temp1.xml"));
transformer.transform(source, result);
}
My app shows stopped running when executing this and so I put in the piece of if block with textview and relative layout("mentioned as "HERE") to see where until the code works fine..The getDocumentElement()does return a value and so it displays in textview as
hiii888org.apache.harmony.xml.dom.ElementImpl#e58aa2f
I dont know why this is coming.I also used Text to typecast and retrieve the result and also .toString() function expecting typecasting can solve the problem.Nothing seem to work..Have been trying Xml update now for days...Hope to see answers that can sort my issue regarding xml update other than the already existing ones...Thanks in advance.

Load strings.xml from sd card to application android

Is it possible to load strings.xml from sd card instead of application res/values/... Search on the web but didn't find any tutorials. My thought is download the xml to sd card then save the strings element to an array.
public void stringsxml(){
File file = new File(Environment.getExternalStorageDirectory()
+ ".strings.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}
Well, actually it is semi-possible, but you have to create a derivate LayoutInflater which will replace string codes with thus read strings.
I have documented my attempts and failings together with initial implementation here.
Summary: simple strings work, string arrays do not
No, this is not possible. Check Android decoumentation about resources:
The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application.
Resources are built-in into the application binary and you can't read them from a file.

Encoding issue on Kit Kat / Android when saving and reading a webview

I have noticed that for Android 4.4 handsets, saving a webview with:
webview.saveWebArchive(name);
and reading it after with WebArchiveReader WebArchiveReader (see code below) throws an Encoding Exception:
11-08 15:10:31.976: W/System.err(2240): org.xml.sax.SAXParseException: Unexpected end of document
11-08 15:10:31.976: W/System.err(2240): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:125)
The method used to read the stored XML file worked perfectly fine until 4.3 and it is (NOTE: I tried to parse it in two different ways):
public boolean readWebArchive(InputStream is) {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
myDoc = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
//New attempt
InputSource input = new InputSource(is);
input.setEncoding("UTF-8");
myDoc = builder.parse(input);
//This used to be the way it used to work for
//Android 4.3 and below without trouble
//myDoc = builder.parse(is);
NodeList nl = myDoc.getElementsByTagName("url");
for (int i = 0; i < nl.getLength(); i++) {
Node nd = nl.item(i);
if(nd instanceof Element) {
Element el = (Element) nd;
// siblings of el (url) are: mimeType, textEncoding, frameName, data
NodeList nodes = el.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node node = nodes.item(j);
if (node instanceof Text) {
String dt = ((Text)node).getData();
byte[] b = Base64.decode(dt, Base64.DEFAULT);
dt = new String(b);
urlList.add(dt);
urlNodes.add((Element) el.getParentNode());
}
}
}
}
} catch (SAXParseException se){
//Some problems parsing the saved XML file
se.printStackTrace();
myDoc = null;
} catch (Exception e) {
e.printStackTrace();
myDoc = null;
}
return myDoc != null;
}
I've played a bit with the way the buider is invoked. Instead of giving it a FileInputStream, I first create an InputSource as you can see to force a given encoding. However, I had no success. By not including the InputSource, the exception was instead:
org.xml.SAXParseException: Unexpected token
I've read in previous posts that this may be an encoding issue (e.g. android-utf-8-file-parsing) but none of the proposed solutions worked for me.
Does anyone else have the same issue or does anyone know what has changed on Kit Kat, and if so, how could it be avoided?
Many thanks in advance
My WebArchiveReader code is not needed under Android 4.4 KitKat and newer to read back a saved web archive. If you save your page with webview.saveWebArchive(name); method on KitKat, you get an MHTML formatted file, as "#Dragon warrior" indicates above. To read this file back into webview, just use:
webView.loadUrl("file:///my_folder/mySavedPage.mht");
Just make sure to give your file the .mht or .mhtml extension, so that WebView recognizes its contents. Otherwise it may just display the MHTML code in text format.
Greg
I have the exactly same problem as you do.
Apparently, Android 4.4 WebView saves web archives as MHTML. Therefore, you can't use WebArchiveReader anymore.
You might want to parse MHTML files with some other 3rd party lib. Good luck!

Accessing Storage on the Nook

The closest thing to documentation I can find having to do with file storage is this post (see below if you can't access it), but it leaves me with several questions.
I would really, really, really like a knowledgeable explanation of what paths map to what storage here, seeing as how we're supposed to hard-code them, and how precisely we're expected to access them. An actual code sample would be superlative. My best guess from messing around with this is that:
/sdcard-> maps to the internal eMMC slot, and access is restricted.
Environment.getExternalStorageDirectory(); ... still returns this.
/media -> maps to the internal 8GB memory (I can write to this)
/data -> ?
? -> maps to the optional microSD card
How can we access the external (optional, additional, the one you can pop out) sdcard, if /sdcard maps to restricted storage instead?
Now to quote the Nook developer docs:
Background There are two different partition schemes for the NOOK
Color devices in market today, one with only 250MB available to
applications on the /data partition and one with 4GB available to
applications on the /data partition. As a result, it is imperative
that applications are designed and developed in such a way as to
manage space effectively. Applications which fail to do so will not be
accepted for distribution via the Shop.
Area Associated Technical Recommendation or Solution if your
application requires large amount of data (including but not limited
to images, audio or video content), you should download those
resources at runtime and store them in the larger partition of the
device. If your application is going to request and store more than
100MB of data or resource you MUST abide by the the following
restrictions:
Your application must clearly and explicitly state in the description
provided that a large amount of data is used/delivered by the
application. You MUST write your resources and data onto appropriate
partition. You can detect if the device has an enlarged /data
partition as follows :
StatFs stat = new StatFs("/data");
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
if (megAvailable > 1000){
... write your resources in /data
} else {
... write your resources on /mnt/media ...
}
To write data into your application's private space on /data
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
Your application should NOT assume the
presence of an sdcard on device, but you can test for one via a call
to
Environment.getExternalStorageState(); If an SD Card is not found,
your application MUST exit gracefully with a notification to the user
as to the reason for the exit.
Remember, that to access the /media partition, as well as
ExternalStorage you need to declare in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
Okay, here's what I've learned in the past couple of weeks.
If you want to write to the internal SDcard, use Context.getFilesDir(). It'll return the private directory for your application. You can not invent your own directories on the internal flash storage (aka "/data"). You don't have permission to write anywhere other than the folder your application gets assigned. Supposedly there are two internal partitions, "/data" and "/media", but I can't get at "/media" to save my life.
You can use the external flash memory, "/sdcard", when one is available. This is the card you can pop out of the device. There are two ways to go about this:
Store things in the folder assigned to your app (so it'll get deleted
when your application is uninstalled). You can find that folder with
Context.getExternalFilesDir().
Store things wherever, either in some hard-coded path under "/sdcard/foo/bar" or in
Environment.getExternalStorageDirectory() / whatever.
This post by a B&N rep (which I referenced in my question) turned out to be a bit of a red herring, "/sdcard" doesn't map to the eMMC slot, and I have no idea what "we mapped the SD card to our internal eMMC" means.
This B&N post says that "/media" is internal, but I can't write to it even though I have the proper manifest permissions... so go figure.
This is a screencap of my test device, showing what is and isn't accessible:
The code for that (note that FileUtils isn't included in the sdk by default,it's from the org.apache.commons.io lib):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView dataView = (TextView) findViewById(R.id.data);
dataView.setText(testIt("/data"));
TextView mediaView = (TextView) findViewById(R.id.media);
mediaView.setText(testIt("/media"));
TextView mntMediaView = (TextView) findViewById(R.id.mntMedia);
mntMediaView.setText(testIt("/mnt/media"));
try {
File fd = this.getFilesDir();
if(fd != null) {
TextView fdView = (TextView) findViewById(R.id.filesDir);
fdView.setText("getFilesDir(): " + testIt(fd.toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File efd = this.getExternalFilesDir(null);
if(efd != null) {
TextView efdView = (TextView) findViewById(R.id.externalFilesDir);
efdView.setText("getExternalFilesDir(): " + testIt(efd.toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File esd = Environment.getExternalStorageDirectory();
if(esd != null) {
TextView esdView = (TextView) findViewById(R.id.externalStorageDirectory);
esdView.setText("getExternalStorageDirectory(): " + testIt(esd.toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File espd = Environment.getExternalStoragePublicDirectory(null);
if(espd != null) {
TextView espdView = (TextView) findViewById(R.id.externalStoragePublicDirectory);
espdView.setText("getExternalStoragePublicDirectory(): " + testIt(espd.toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String testIt(String dir){
StatFs stat = new StatFs(dir);
long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getBlockCount();
long megAvailable = bytesAvailable / FileUtils.ONE_MB;
File dirFile = new File(dir + "/test/");
dirFile.mkdir();
return dir + "/test \n canRead() " + dirFile.canRead() + ", \n canWrite() " + dirFile.canWrite() + " with " + megAvailable + "MB available";
}
First of all try the following methods:
Context.getExternalFilesDir
Context.getExternalCacheDir
Environment.getExternalStoragePublicDirectory
If neither of those return you a directory where you can write to, check the following google-groups thread, and use the code provided in the last answer, which enumerates all current mount-points:
I have the same issue with Galaxy S. Until now all Android devices I
got have "mount" command available. I build a list of available volume
parsing "mount" response. This is not perfect but cleaver than Android
storage API.
String cmd = "/system/bin/mount";
try {
Runtime rt = Runtime.getRuntime();
Process ps = rt.exec(cmd);
BufferedReader rd = new BufferedReader( new InputStreamReader(ps.getInputStream()) );
String rs;
while ((rs = rd.readLine()) != null)
{
//check what you need!
Log.i("MOUNT_CMD", rs);
}
rd.close();
ps.waitFor();
} catch(Exception e) {
//...
}
If it is possible to insert the microSD card in the Nook device, while it is running, you could also try the following:
mVolumeManagerReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.i("MediaMounter", "Storage: " + intent.getData());
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addDataScheme("file");
context.registerReceiver(mVolumeManagerReceiver, filter);

Categories

Resources