React native search for documents(.pdf, .doc, .xlsx) in device - android

I am working on an app to get all documents like .pdf .doc .docx .ppt .pptx .xls .txt .xlsx. ihave tried rn-fetch-blob and react-native-fs but there are giving only directory status.
useEffect(() => {
const fetchdocuments = async () => {
RNFetchBlob.fs.lstat(RNFetchBlob.fs.dirs.SDCardDir).then((data) => {
data.forEach(element => {
console.log(element)
});
}).catch((error) => {
console.log(error)
})
}
fetchdocuments()
},[])
I also tried this library react-native-get-music-files but it returns only the mediastore file API for android but don't know how to implement this in react-native. any help will be really appreciated.

here I have created a native module for this. code is given below
package com.dconverter;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import java.util.Objects;
public class CustomerMediaStore extends ReactContextBaseJavaModule implements ActivityEventListener {
private final ReactApplicationContext reactContext;
private int version = Build.VERSION.SDK_INT;
#Override
public String getName() {
return "CustomerMediaStore";
}
public CustomerMediaStore(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
}
#ReactMethod
public void GetFiles(final Callback successCallback, final Callback errorCallback){
if(version <= 19){
getSongs( successCallback, errorCallback);
}else{
Thread bgThread = new Thread(null, new Runnable() {
#Override
public void run() {
getSongs(successCallback, errorCallback);
}
}, "asyncTask", 1024);
bgThread.start();
}
}
private void getSongs (final Callback successCallback, final Callback errorCallback) {
ContentResolver musicResolver = reactContext.getApplicationContext().getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
try {
WritableArray jsonArray = new WritableNativeArray();
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATE_MODIFIED,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.SIZE,
};
String mimeType = "application/pdf";
String selection = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')"
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd%'" // .docx , .xlsx , .pptx .xls
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE '%application/msword'" // .doc
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/mspowerpoint'" // .ppt
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'text/plain'" // .txt
// + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE '%/%'" // all type of douments audio/vidoe/ evey thing
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/rtf'" // wordpad
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'font/otf'" // .otf
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd.oasis.opendocument.spreadsheet'" // .ods
+ " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd.oasis.opendocument.text'" // .otd
;
String orderBy = MediaStore.Files.FileColumns.DATE_ADDED;
Cursor cursor = musicResolver.query(uri, projection, selection,null,orderBy);
if (cursor != null && cursor.getCount() > 0) {
Log.e("Musica", String.valueOf(cursor.getCount()));
cursor.moveToFirst();
do {
WritableMap item = new WritableNativeMap();
item.putString("id", String.valueOf(cursor.getString(0)));
item.putString("minetype", String.valueOf(cursor.getString(1)));
item.putString("dateadded", String.valueOf(cursor.getString(2)));
item.putString("datemodified", String.valueOf(cursor.getString(3)));
item.putString("displayname", String.valueOf(cursor.getString(4)));
item.putString("uri",String.valueOf(cursor.getString(5)));
item.putString("title", String.valueOf(cursor.getString(6)));
item.putString("size", String.valueOf(cursor.getString(7)));
jsonArray.pushMap(item);
} while (cursor.moveToNext());
} else {
String msg = "cursor is either null or empty ";
Log.e("Musica", String.valueOf(cursor.getCount()));
}
cursor.close();
successCallback.invoke(jsonArray);
}catch (Exception e) {
errorCallback.invoke(e.getMessage());
Log.e("Musica", e.getMessage());
}
}
#RequiresApi(api = Build.VERSION_CODES.R)
#ReactMethod private void checkStorgePermision(Promise promise){
}
#RequiresApi(api = Build.VERSION_CODES.R)
#ReactMethod private void checkStorgaePermission(Promise promise){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
promise.resolve(Environment.isExternalStorageManager());
}
}
#ReactMethod
private void askforscopestoragepermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if(!Environment.isExternalStorageManager())
{
askAndroid11StoragePermission(reactContext);
}
}
}
#RequiresApi(Build.VERSION_CODES.R)
private void askAndroid11StoragePermission(Context context )
{
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data",Uri.parse(String.format("package:%s",context.getApplicationContext().getPackageName())));
getReactApplicationContext().startActivityForResult(intent,2296, null);
}
catch (Exception e){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getReactApplicationContext().startActivityForResult(intent,2296, null);
}
}
// #Override
// protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == 2296) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// if (Environment.isExternalStorageManager()) {
// // perform action when allow permission success
// } else {
//
// }
// }
// }
// }
#Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
Log.e("Musics", String.valueOf(requestCode + requestCode));
}
#Override
public void onNewIntent(Intent intent) {
}
}
Here is the usage example
import React, { useEffect, useState } from 'react';
import {
SafeAreaView,
PermissionsAndroid,
StatusBar,
StyleSheet,
Text,
View,
FlatList,
NativeModules,Platform, addons
} from 'react-native';
const {CustomerMediaStore} = NativeModules;
const calculateSize = (bytes, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
const Item = ({ title, dateadded, datemodified, size }) => {
let dateModified = (new Date(datemodified*1000));
let dateAdded = new Date(dateadded*1000)
return (
<View style={styles.item}>
<Text style={styles.title}>Name: {title}</Text>
<Text>Date Modified: {('0' + dateModified.getUTCDate()).slice(-2) + '-' + ('0' + dateModified.getUTCMonth()).slice(-2) + '-' + dateModified.getUTCFullYear() }</Text>
<Text>Date Added: {('0' + dateAdded.getUTCDate()).slice(-2) + '-' + ('0' + dateAdded.getUTCMonth()).slice(-2) + '-' + dateAdded.getUTCFullYear() }</Text>
<Text>Size: {calculateSize(size*1)}</Text>
</View>
)}
const App = () => {
const [data, setData] = useState([])
useEffect(() => {
requestCameraPermission()
},[])
const requestCameraPermission = async () => {
if(Platform.OS === "android"){
if(Platform.Version >= "29"){
CustomerMediaStore.checkStorgaePermission().then( async(data) => {
if(!data){
CustomerMediaStore.askforscopestoragepermission();
}else{
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: "Document Reader App Storage Permission",
message:
"Cool Photo App needs access to your Storage" +
"so you can take awesome pictures.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
console.log(granted)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
try {
myGetFiles().then((data) => {
console.log(data.length,"length")
setData(data)
}).catch((err) => {
console.log(err,"error")
})
}
catch (err) {
console.log(err)
}
} else {
console.log("Storage Permission is required permission denied");
}
} catch (err) {
console.warn(err);
}
}
})
}else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: "Document Reader App Storage Permission",
message:
"Cool Photo App needs access to your Storage" +
"so you can take awesome pictures.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
try {
myGetFiles().then((data) => {
console.log(data.length)
setData(data)
}).catch((err) => {
console.log(err,"error")
})
}
catch (err) {
console.log(err)
}
} else {
console.log("Storage Permission is required permission denied");
}
} catch (err) {
console.warn(err);
}
}
}else {
console.log("ios Setting here");
}
};
const myGetFiles = () => {
return new Promise((resolve, reject) => {
if (Platform.OS === "android") {
CustomerMediaStore.GetFiles(
tracks => {
resolve(tracks);
},
error => {
reject(error);
}
);
}
});
}
const renderItem = ({ item }) => {
return (
<Item title={item.displayname} dateadded={item.dateadded} datemodified={item.datemodified} size={item.size} />
)
}
return (
<SafeAreaView style={styles.container}>
<FlatList
data={[...data]}
renderItem={renderItem}
keyExtractor={item => `${item.id}${+ new Date(item.id*1)}`}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 15,
},
});
export default App;

Related

save a temp file to download file Android/IOS in flutter

I have a question, I am using Path-provider to generate a path for a new generated PDF file from my App… but path provider is storing the file in the App folder & after closing the app the file will be deleted, I am using getExternalStorageDirectory… how can I save that file to downloads when selected.
Anybody can help me?
just small explanation... the PDF file will be viewed from the App using
flutter_full_pdf_viewer
then from that page I need to let the user select if he wants to save the file or close the hall file.
This is the code for the file save
try {
final dir = await getExternalStorageDirectory();
String documentPath = dir.path;
fullPath = "$documentPath/$fileName";
final file = File('$fullPath');
await file.writeAsBytes(await pdf.save());
print('XXXXXXXXX$fileName');
return file;
} catch (e) {
// print('we have a problem');
}
print(fullPath);
}
And this is the PDFViewer page code
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: PDFViewerScaffold(
appBar: AppBar(
title: Text('PDF page'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.shareFiles(
['$path'],
);
print('iiiiiiiiiiiiii$path');
},
),
IconButton(
icon: Icon(Icons.save),
onPressed: () {},
),
],
),
path: path,
),
),
);
}
}
============================================================================
after I modified the code now it looks like this for the PDF_save Page (for Methods)
Future<bool> saveFolder(String fileName) async {
Directory directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
directory = await getExternalStorageDirectory();
String newPath = "";
print('ZZZZZZZZzzzzZZZZz$directory');
List<String> paths = directory.path.split("/");
for (int x = 1; x < paths.length; x++) {
String folder = paths[x];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = newPath + "/SAMApp";
directory = Directory(newPath);
print('AAAAAAAAAAAAAAAA$newPath');
print('AAAAAAAAAAAAAAAA$fileName');
} else {
return false;
}
} else {
if (await _requestPermission(Permission.photos)) {
directory = await getTemporaryDirectory();
} else {
return false;
}
}
File saveFile = File(directory.path + "/$fileName");
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
// await dio.download(saveFile.path, onReceiveProgress: (value1, value2) {
// setState(() {
// progress = value1 / value2;
// });
// });
// if (Platform.isIOS) {
// await ImageGallerySaver.saveFile(saveFile.path,
// isReturnPathOfIOS: true);
// }
File savedFile = File(directory.path + "/$fileName");
var savedPath = directory.path + "/$fileName";
print('$savedPath');
print('$savedFile');
savedFile.writeAsBytesSync(byteList);
if (savedPath != null) {
print('NO saved Path');
// await Navigator.pushReplacement(
// context,
// MaterialPageRoute(
// builder: (context) => SharePage(
// imageFilebytes: pngBytes,
// imagePath: savedPath,
// )),
// );
} else {
print("waiting for savedpath");
}
return true;
}
return false;
} catch (e) {
print(e);
return false;
}
}
did I made something wrong??
This is worked to save the image. It can be useful for you.
Future<bool> saveFile(var byteList, BuildContext context) async {
Directory storageDir;
try {
if (await requestPermission(Permission.storage)) {
storageDir = await getExternalStorageDirectory();
String newPath = '';
List<String> folders = storageDir.path.split('/');
for (int x = 1; x < folders.length; x++) {
String folder = folders[x];
if (folder != 'Android') {
newPath += '/' + folder;
} else {
break;
}
}
newPath = newPath + '/xyz';
storageDir = Directory(newPath);
} else {
if (await requestPermission(Permission.photos)) {
storageDir = await getTemporaryDirectory();
} else {
return false;
}
}
if (!await storageDir.exists()) {
await storageDir.create(recursive: true);
}
if (await storageDir.exists()) {
//List<int> bytesSync = widget.pickedImage.readAsBytesSync();
DateTime date = DateTime.now();
String baseFileName = 'abc' + date.toString() + ".jpg";
File savedFile = File(storageDir.path + "/$baseFileName");
savedPath = storageDir.path + "/$baseFileName";
savedFile.writeAsBytesSync(byteList);
if (savedPath != null) {
await Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SharePage(
imageFilebytes: pngBytes,
imagePath: savedPath,
)));
} else {
print("waiting for savedpath");
}
return true;
}
} catch (e) {
print(e);
}
return false;
}

Exchange rate currency format setting in Flutter

I have an exchange rate application in flutter, but I want to make the currency format the same as below, how can I do it?
My Code :
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import '../Utils.dart';
class CurrencyInputFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.selection.baseOffset == 0) {
print(true);
return newValue;
}
double value = double.parse(newValue.text);
final formatter = NumberFormat("#,##0", "tr-TR");
String newText = formatter.format(value);
print(newText);
return newValue.copyWith(
text: newText,
selection: new TextSelection.collapsed(offset: newText.length));
}
}
I want to do
Intl actually provides you a way to do so.
import 'package:intl/intl.dart';
final moneyText = 1000;
NumberFormat.simpleCurrency().format(moneyText);
If you are already using translation, you should have intl already.
You can achieve this with flutter_masked_text package it can do exactly the same.
I solved. works great.
library currency_text_input_formatter;
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
/// The `symbol` argument is used to symbol of NumberFormat.
/// Put '\$' for symbol
///
/// The `locale` argument is used to locale of NumberFormat.
/// Put 'en' or 'es' for locale
///
/// The `decimalDigits` argument is used to decimalDigits of NumberFormat.
/// Defaults `decimalDigits` is 2.
class CurrencyTextInputFormatter extends TextInputFormatter {
#override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
return newValue.copyWith(text: '');
} else if (newValue.text == ".") {
return newValue.copyWith(
text: '0.00',
selection: TextSelection.collapsed(offset: 2),
);
} else {
NumberFormat f = NumberFormat("#,###,###.00", "en_US");
double newNumber = 0;
if ((!newValue.text.contains(".")) && oldValue.text.contains('.')) {
String tempString = newValue.text.replaceAll(f.symbols.GROUP_SEP, '');
tempString = tempString.substring(0, tempString.length - 2) +
"." +
tempString.substring(tempString.length - 2);
newNumber = double.parse(tempString);
} else {
newNumber = double.parse(newValue.text
.replaceAll(f.symbols.GROUP_SEP, '')
.replaceAll("..", '.'));
}
String newString = f.format(newNumber);
int cursorPosition = 0;
if (oldValue.text.length > newString.length) {
cursorPosition = -1;
} else if (oldValue.text.length < newString.length) {
cursorPosition = 1;
} else {
if (oldValue.text.replaceAll(f.symbols.GROUP_SEP, '').length >
newValue.text.replaceAll(f.symbols.GROUP_SEP, '').length) {
cursorPosition = -1;
if (newString == "0.00" && oldValue.selection.baseOffset == 0) {
newString = "";
}
} else if (oldValue.text.replaceAll(f.symbols.GROUP_SEP, '').length <
newValue.text.replaceAll(f.symbols.GROUP_SEP, '').length) {
cursorPosition = 1;
} else if (oldValue.selection.extentOffset >
oldValue.selection.baseOffset) {
cursorPosition =
oldValue.selection.baseOffset - oldValue.selection.extentOffset;
newString =
newString.substring(0, oldValue.selection.baseOffset - 1) +
newString.substring(oldValue.selection.baseOffset + 1);
newNumber = double.parse(newString
.replaceAll(f.symbols.GROUP_SEP, '')
.replaceAll("..", '.'));
newString = f.format(newNumber);
if (newString == "0.00" && oldValue.selection.baseOffset == 0) {
newString = "";
}
}
}
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: oldValue.selection.extent.offset +
cursorPosition +
(f.symbols.GROUP_SEP.allMatches(newString).length -
f.symbols.GROUP_SEP.allMatches(oldValue.text).length)),
);
}
}
}

How do you print/output returned Raw text from a React Module function(Get Call Log)?

I'm creating a react native android application to access and print out an android phone/tablet's call logs in a sectionlist for the day/date (eg. Yesterday; 26/07/17; 25/07/17 etc);but I am stuck at the actual printing out of the string of call logs in the react class - when invoking the method from the module. Apparently react methods can only "return" void.
I tried to use promises but got stuck with async and await. I can't use npm 5(node which has async and await) because I created a project using "react native init" for the physical device testing; and npm is not supported/stable(shown on terminal). I used "sudo npm install -g npm#latest-4" so I could use init .
I tried installing async and await manually using "npm install async --save" and "npm install asyncawait". When I ran later it made no difference.
I really just want to output the call details as a sectionlist on the screen of my physical android device.
I've tried google; but maybe my keywords were not good enough; so I got little help. It would also be nice if you could give me an indication of whether a .xml file is needed and if so; how it would look. I've posted my code for the java native module method and the Class where I import the module from a helper .js class. I apologise for the commented code; I tried many methods to print.
The latest error I was getting; when I could actually toast the ' tag' was "undefined is not an object (evaluating 'n.data.length')". This after resolving "expected a component class got object" and "undefined is not a function".
React js class below:
import React, { Component } from 'react';
import { NativeModules, AppRegistry, SectionList, StyleSheet, Text, View, WebView } from 'react-native';
import { StackNavigator, } from 'react-navigation';
import CallLogAndroid from './RctActivity';
export default class SectionListBasics extends Component {
static navigationOptions = { title: 'Your Call Logs', };
// CallLog = () =>{
// const Cllog= CallLogAndroid.getCallDetails();
// console.log(Cllog+"");
// return Cllog+"";
// };
// async function getCallLog() {
// try {
// var CallDetails = await CallLogAndroid.getCallDetails(100, 100);
// console.log(CallDetails);
// return CallDetails;
// }
// catch (e) {
// console.error(e);
// }
// }
componentWillMount() {
const log = CallLogAndroid.getCallDetails().then(function(value) {
console.log(value); // "Success"
}, function(value) {
// not called
});
}
render() {
// const divStyle = {
// WebkitTransition: 'all', // note the capital 'W' here
// msTransition: 'all' // 'ms' is the only lowercase vendor prefix
// };
// var thenProm = resolvedProm.then(function(value){
// console.log("this gets called after the end of the main stack. the value received and returned is: " + value);
// return value;
// });
console.log(this.log+"");
//getCallLog();
return (
<View style={styles.container}>
<SectionList
sections={[
{title: 'Today', data: [ 'pete'{/*this.log*/}] },
{/* <WebView source={{html: CallLogAndroid.getCallDetails()}} /> */},
{title: 'Yesterday', data: ['Jackson']},
{title: 'Date: 1', data: ['water']},
{title: 'Date: 2', data: ['dance']},
{title: 'Date: 3', data: ['rain']},
{title: 'Date: 4', data: ['Mum']},
{title: 'Date: 5', data: ['Dad']},
]}
renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
/>
{/* <Text>
console.log(CallLogAndroid.getCallDetails().toString());
</Text> */}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
sectionHeader: {
paddingTop: 2,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 2,
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'rgba(247,247,247,1.0)',
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
// skip this line if using Create React Native App
//AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);
Here is the java class:
package com.workingapp;
import android.widget.Toast;
//to create react bridge
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.bridge.Promise;
//android tools imports
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.database.Cursor; //import cursor to parse call logs
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.os.Bundle;
import android.text.Html; //import html to make *online query to content provider
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.widget.ImageView;
import android.view.Gravity; //import gravity to centre layout
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Map;
import java.net.*; //import uri - a Uniform Resource Identifier (URI) is a string of characters used to identify a resource. Such identification enables interaction with representations of the resource over a network
import java.util.Date;
import android.widget.TextView;
import java.util.HashMap;
//Customised versions of loader imported
import android.support.v4.app.FragmentActivity;
//import android.support.v4.app.LoaderManager;
//import android.support.v4.content.Loader;
//Specific imports for inflator in toast
import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class CallLogModule extends ReactContextBaseJavaModule implements LoaderManager.LoaderCallbacks<Cursor>{
public static final String REACT_CLASS = "CallLogAndroid";
private static final String E_LAYOUT_ERROR = "E_LAYOUT_ERROR";
ReactApplicationContext reactContext;
private static HashMap<String, String> rowDataCall;
private static final String TAG = "CallLog";
private static final int URL_LOADER = 1;
private static TextView callLogsTextView;
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// Log.d(TAG, "onCreate()");
// setContentView(R.layout.main);
// initialize();
// }
/**Constructor */
public CallLogModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext= reactContext;
//(Activity)reactContext.setContentView(R.layout.module_layout);
}
/**Loads all calls */
#Override
#ReactMethod
public Loader onCreateLoader(int loaderID, Bundle args) {
Log.d(TAG, "onCreateLoader() >> loaderID : " + loaderID);
switch (loaderID) {
case URL_LOADER:
// Returns a new CursorLoader
return new CursorLoader(
reactContext, // Parent activity context
CallLog.Calls.CONTENT_URI, // Table to query
null, // Projection to return
null, // No selection clause
null, // No selection arguments
null // Default sort order
);
default:
return null;
}
}
/**On completing load, return/output formatted string*/
#Override
#ReactMethod
public void onLoadFinished(Loader loader, Cursor managedCursor) {
Log.d(TAG, "onLoadFinished()");
StringBuilder sb = new StringBuilder();
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("<h4>Call Log Details <h4>");
sb.append("\n");
sb.append("\n");
sb.append("<table>");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
//Date callDayTime = new Date(Long.valueOf(callDate));
Date callDayTime= null;
if( (!callDate.trim().equals("") ) && (callDate != null)) {
callDayTime = new Date(Long.valueOf(callDate)); //if value of long is null
}
String callDuration = managedCursor.getString(duration);
String dir = null;
int callTypeCode = Integer.parseInt(callType);
switch (callTypeCode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "Missed";
break;
}
sb.append("<tr>")
.append("<td>Phone Number: </td>")
.append("<td><strong>")
.append(phNumber)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Call Type:</td>")
.append("<td><strong>")
.append(dir)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Date & Time:</td>")
.append("<td><strong>")
.append(callDayTime)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Call Duration (Seconds):</td>")
.append("<td><strong>")
.append(callDuration)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<br/>");
}
sb.append("</table>");
managedCursor.close();
callLogsTextView.setText(Html.fromHtml(sb.toString()),TextView.BufferType.SPANNABLE);
}
#Override
#ReactMethod
public void onLoaderReset(Loader<Cursor> loader) {
Log.d(TAG, "onLoaderReset()");
// do nothing
}
/**Method to obtain name of the class */
#Override
public String getName() {
return REACT_CLASS;
}
/**Method to get entire call log */
// #ReactMethod
// public void getCallLog(String phone,int duration) {
// //Checking if permission was denied
// if (ActivityCompat.checkSelfPermission(getCurrentActivity(), Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED){
// ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{Manifest.permission.READ_CALL_LOG}, 101);
// }
// //uses a cursor to get all calls
// else{
// Uri allCalls = Uri.parse("content://call_log/calls");
// Cursor c = managedQuery(allCalls, null, null, null, null);
// //separates calls according to number; name; duration and Call type
// String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
// String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
// String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
// int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out-going.
// //Print calls in a certain format
// }
// }
/**Method to get full list of call logs */
#ReactMethod
private void getCallDetails(Promise promise) {
try{
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = (reactContext.getCurrentActivity()).getContentResolver().query(contacts, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
//sb.append("Call Details :");
sb.append("<h1>Call Log Details </h1>"); //tried to print out with react syntax contrary to code commented below
sb.append("\n");
sb.append("\n");
sb.append("<table>");
while (managedCursor.moveToNext()) {
rowDataCall = new HashMap<String, String>();
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
String callDayTime = new Date(Long.valueOf(callDate)).toString();
// long timestamp = convertDateToTimestamp(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
// sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
// sb.append("\n----------------------------------");
sb.append("<tr>")
.append("<td>Phone Number: </td>")
.append("<td><strong>")
.append(phNumber)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Call Type:</td>")
.append("<td><strong>")
.append(dir)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Date & Time:</td>")
.append("<td><strong>")
.append(callDayTime)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<tr>")
.append("<td>Call Duration (Seconds):</td>")
.append("<td><strong>")
.append(callDuration)
.append("</strong></td>");
sb.append("</tr>");
sb.append("<br/>");
sb.append("<br/>");
}
sb.append("</table>");
managedCursor.close();
String clLog=sb.toString();
promise.resolve(clLog);
}
catch (IllegalViewOperationException e) { promise.reject(E_LAYOUT_ERROR, e); }
//System.out.println(sb.toString());
// callLogsTextView.setText(Html.fromHtml(sb.toString()));
// WebView webview = new WebView(reactContext.getCurrentActivity());
// webview.loadData(sb.toString(), "text/html", "utf-8");
//Toast.makeText(reactContext, sb.toString(), Toast.LENGTH_LONG).show();
// LayoutInflater inflater = reactContext.getCurrentActivity().getLayoutInflater();
// View layout = inflater.inflate(R.layout.module_layout,
// (ViewGroup) reactContext.getCurrentActivity().findViewById(R.id.custom_toast_container));
//
// ImageView image = (ImageView) layout.findViewById(R.id.image);
// image.setImageResource(R.drawable.android);
// TextView text = (TextView) layout.findViewById(R.id.text);
// text.setText(sb.toString());
//
// Toast toast = new Toast(reactContext.getCurrentActivity());
// toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
// toast.setDuration(Toast.LENGTH_LONG);
// toast.setView(layout);
// toast.show();
}
}
I figured it out. I was mixing up promises and callback code.
I used promises again and it worked.
const log = CallLogAndroid.getCallDetails().then(function(value) {
console.log(value);
".then(function(..." is used to resolve a call back. It was not supposed to be added and an async function had to be used. With promises; just calling the function should return the data.

Ionic app does not work properly on android device

I am new to ionic 1. I have been making an app where I have used SQLite. The app runs perfectly on browser but works partially on device. There is a button that does not work. The code that contains this button is given below. The button function name is charge. Here's my code:
angular.module('app.cartCtrl', ['ngCordova'])
.controller('cartCtrl', ['$scope', '$stateParams', '$state', '$cordovaSQLite', '$ionicHistory', '$ionicPopup',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
$stateParams.parameterName
function ($scope, $stateParams, $state, $cordovaSQLite, $ionicHistory, $ionicPopup) {
$scope.items = [];
$scope.grandTotal = 0;
$scope.receiptnumber = 0;
$scope.receiptnumber = $scope.receiptnumber + 1;
$scope.items = [];
$scope.item = {};
$scope.grandTotal = null;
var query2 = "SELECT * FROM items WHERE quantity!='' ";
console.log(query2);
$cordovaSQLite.execute(db, query2, []).then(function (res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
$scope.items.push({
itemname: res.rows.item(i).itemname,
price: res.rows.item(i).price,
quantity: res.rows.item(i).quantity,
});
$scope.items = $scope.items;
}
} else {
console.log("No results found");
}
}, function (err) {
console.error("error=>" + err);
});
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
var query = "SELECT SUM(total) FROM items";
$cordovaSQLite.execute(db, query, []).then(function (res) {
$scope.grandTotal = res.rows[0]['SUM(total)'];
//$scope.grandtotal = parseFloat(res.rows[0]['SUM(total)']);
// console.log("Grand total is" + res.rows[0]['SUM(total)']);
}, function (err) {
console.error("error=>" + err);
});
$scope.myGoBack = function () {
$state.go("menu.sales");
};
$scope.charge = function () {
$state.go('transactionsuccess');
}
}])
I am in doubt with below piece of code. Will it work on device or emulator:
res.rows[0]['SUM(total)']
Try with this updated query and check the post the log what ur getting
var query2 = "SELECT * FROM items WHERE quantity!='' ";
console.log(query2);
$cordovaSQLite.execute(db, query2, [5]).then(function (res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
$scope.items.push({
itemname: res.rows.item(i).itemname,
price: res.rows.item(i).price,
quantity: res.rows.item(i).quantity,
});
$scope.items = $scope.items;
}
} else {
console.log("No results found");
}
}, function (err) {
console.error("error=>" + err);
});
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
var query = "SELECT SUM(total) total FROM items";
$cordovaSQLite.execute(db, query, []).then(function (res) {
console.log('Result: ', res);
$scope.grandTotal = res.rows[0].total;
//$scope.grandtotal = parseFloat(res.rows[0]['SUM(total)']);
// console.log("Grand total is" + res.rows[0]['SUM(total)']);
}, function (err) {
console.error("error=>" + err);
});

Async with Rotation Support

EDIT: So I tried applying rotation support but every time I rotate my device the dialog pops up any ideas on what I did wrong or why it isn't keeping the dialog from displaying on a orientation change?
package com.ondrovic.bbym;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class Dashboard extends Activity {
public static final boolean usePrettyGoodSolution = false;
private ProgressDialog PROGRESS_BAR;
private Download task = null;
private static final int PROGRESS = 0;
public static File rDIR = Environment.getExternalStorageDirectory();
public static final String fDIR = "/Android/data/Bestbuy Mobile/database/";
public static final String fNAME = "bestbuy.db";
public static final String fURL = "http://db.tt/5JTRpA8q";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
task = (Download) getLastNonConfigurationInstance();
}
#Override
public Object onRetainNonConfigurationInstance() {
task.detach();
return (task);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onRestart() {
super.onRestart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
public void onClickHome(View v) {
goHome(this);
}
public void onClickUpdate(View v) {
dbDIR(fDIR);
//new Download().execute(fURL);
if (task == null) {
task = new Download(this);
task.execute(fURL);
} else {
task.attach(this);
}
}
public void onClickEmail(View v) {
// title_bar email : price quotes :-)
if (getTitle().toString().equals("Individual")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Individual Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Individual Plan"
+ "\nMinutes Package: " + Individual_ATT.packageTalk
+ "\nMessage Package: " + Individual_ATT.packageText
+ "\nData Package: " + Individual_ATT.packageData
+ "\nPrice: " + Individual_ATT.packagePrice
+ "\n\nSprint Individual Plan" + "\nPackage: "
+ Individual_SPRINT.packageInfo + "\nPrice: "
+ Individual_SPRINT.packagePrice
+ "\n\nVerizon Individual Plan" + "\nPackage: "
+ Individual_VERIZON.packageTalk + "\nData: "
+ Individual_VERIZON.packageData + "\nPrice: "
+ Individual_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Family")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Family Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Family Plan"
+ "\nMinutes Pacakge: "
+ Family_ATT.packageTalk
+ "\nMessage Package: "
+ Family_ATT.packageText
+ "\nAdditional Lines: "
+ Family_ATT.packageXtraLn
+ "\nData Package Line 1: "
+ Family_ATT.packageData1
+ "\nData Package Line 2: "
+ Family_ATT.packageData2
+ "\nData Package Line 3: "
+ Family_ATT.packageData3
+ "\nData Pacakge Line 4: "
+ Family_ATT.packageData4
+ "\nData Package Line 5: "
+ Family_ATT.packageData5
+ "\nPrice: "
+ Family_ATT.packagePrice
+ "\n\nSprint Family Plan"
+ "\nPacakge: "
+ Family_SPRINT.packageInfo
+ "\nAdditional Lines: "
+ Family_SPRINT.packageXtraLn
+ "\nLine 1 Type: "
+ Family_SPRINT.packageLine1
+ "\nLine 1 Data: "
+ Family_SPRINT.dataPriceL1
+ "\nLine 2 Type: "
+ Family_SPRINT.packageLine2
+ "\nLine 2 Data: "
+ Family_SPRINT.dataPriceL2
+ "\nLine 3 Type: "
+ Family_SPRINT.packageLine3
+ "\nLine 3 Data: "
+ Family_SPRINT.dataPriceL3
+ "\nLine 4 Type: "
+ Family_SPRINT.packageLine4
+ "\nLine 4 Data: "
+ Family_SPRINT.dataPriceL4
+ "\nLine 5 Type: "
+ Family_SPRINT.packageLine5
+ "\nLine 5 Data: "
+ Family_SPRINT.dataPriceL5
+ "\nPrice: "
+ Family_SPRINT.packagePrice
+ "\n\nVerzon Family Plan"
+ "\nPackage: "
+ Family_VERIZON.packageTalk
+ "\nAdditional Lines: "
+ Family_VERIZON.packageXtraLn
+ "\nData Pacakge Line 1: "
+ Family_VERIZON.packageData1
+ "\nData Pacakge Line 2: "
+ Family_VERIZON.packageData2
+ "\nData Pacakge Line 3: "
+ Family_VERIZON.packageData3
+ "\nData Pacakge Line 4: "
+ Family_VERIZON.packageData4
+ "\nData Pacakge Line 5: "
+ Family_VERIZON.packageData5
+ "\nPrice: "
+ Family_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Broadband")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Broadband Plan Comparison");
email.putExtra(Intent.EXTRA_TEXT, "\nAT&T Broadband Plan"
+ "\nPackage: " + Broadband_ATT.pacakgeData
+ "\nPrice: " + Broadband_ATT.packagePrice
+ "\n\nSprint Broadband Plan" + "\nPackage: "
+ Broadband_SPRINT.pacakgeData + "\nPrice: "
+ Broadband_SPRINT.packagePrice
+ "\n\nVerizon Broadband Plans" + "\nPacakge: "
+ Broadband_VERIZON.pacakgeData + "\nPrice: "
+ Broadband_VERIZON.packagePrice);
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
if (getTitle().toString().equals("Embedded")) {
try {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_SUBJECT,
"BBYM Embedded Plan Comparison");
// email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(new
// StringBuilder()
// .append("<p><b>BBYM Embedded Plan Comparison</b></p>")
// .append("<p>This is a test</>") .toString()));
try {
startActivity(Intent
.createChooser(email, "Send Comparison"));
} catch (android.content.ActivityNotFoundException ex) {
}
} catch (Exception e) {
}
}
}
public void goHome(Context context) {
final Intent intent = new Intent(context, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
#Override
public void setContentView(int layoutID) {
if (!usePrettyGoodSolution) {
super.setContentView(layoutID);
return;
}
#SuppressWarnings("unused")
Configuration c = getResources().getConfiguration();
int size = c.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
boolean isLarge = (size == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean isXLarge = (size == Configuration.SCREENLAYOUT_SIZE_XLARGE);
boolean addFrame = isLarge || isXLarge;
// if (isLarge) System.out.println ("Large screen");
// if (isXLarge) System.out.println ("XLarge screen");
int finalLayoutId = addFrame ? R.layout.large : layoutID;
super.setContentView(finalLayoutId);
if (addFrame) {
LinearLayout frameView = (LinearLayout) findViewById(R.id.frame);
if (frameView != null) {
// If the frameView is there, inflate the layout given as an
// argument.
// Attach it as a child to the frameView.
LayoutInflater li = ((Activity) this).getLayoutInflater();
View childView = li.inflate(layoutID, null);
if (childView != null) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0F);
frameView.addView(childView, lp);
// childView.setBackgroundResource (R.color.background1);
}
}
}
}
public void setTitleFromActivityLabel(int textViewID) {
TextView tv = (TextView) findViewById(textViewID);
if (tv != null) {
tv.setText(getTitle());
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS:
PROGRESS_BAR = new ProgressDialog(this);
PROGRESS_BAR.setTitle("Updater");
PROGRESS_BAR.setMessage("Updating database");
PROGRESS_BAR.setIndeterminate(false);
PROGRESS_BAR.setMax(100);
PROGRESS_BAR.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
PROGRESS_BAR.setCancelable(false);
PROGRESS_BAR.show();
return PROGRESS_BAR;
default:
return null;
}
}
class Download extends AsyncTask<String, String, String> {
Dashboard activity = null;
Download(Dashboard activity) {
attach(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(fURL);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
int fSIZE = con.getContentLength();
FileOutputStream out = new FileOutputStream(new File(rDIR
+ fDIR, fNAME));
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
long total = 0;
while ((len = in.read(buffer)) > 0) {
total += len;
publishProgress("" + (int) ((total * 100) / fSIZE));
out.write(buffer, 0, len);
}
out.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
if (activity == null) {
} else {
PROGRESS_BAR.setProgress(Integer.parseInt(progress[0]));
}
//PROGRESS_BAR.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String fURL) {
dismissDialog(PROGRESS);
}
void detach() {
activity = null;
}
void attach(Dashboard activity) {
this.activity = activity;
}
}
public void dbDIR(String dirName) {
File nDIR = new File(rDIR + dirName);
if (!nDIR.exists()) {
nDIR.mkdirs();
}
}
}

Categories

Resources