android - How do you print/output returned Raw text from a React Module function(Get Call Log)? -
i'm creating react native android application access , print out android phone/tablet's call logs in sectionlist day/date (eg. yesterday; 26/07/17; 25/07/17 etc);but stuck @ actual printing out of string of call logs in react class - when invoking method module. apparently react methods can "return" void.
i tried use promises got stuck async , await. can't use npm 5(node has async , await) because created project using "react native init" physical device testing; , npm not supported/stable(shown on terminal). used "sudo npm install -g npm@latest-4" use init .
i tried installing async , await manually using "npm install async --save" , "npm install asyncawait". when ran later made no difference.
i want output call details sectionlist on screen of physical android device.
i've tried google; maybe keywords not enough; got little help. nice if give me indication of whether .xml file needed , if so; how look. i've posted code java native module method , class import module helper .js class. apologise commented code; tried many methods print.
the latest error getting; when toast ' tag' "undefined not object (evaluating 'n.data.length')". after resolving "expected component class got object" , "undefined not function".
react js class below:
import react, { component } 'react'; import { nativemodules, appregistry, sectionlist, stylesheet, text, view, webview } 'react-native'; import { stacknavigator, } 'react-navigation'; import calllogandroid './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 capital 'w' here // mstransition: 'all' // 'ms' lowercase vendor prefix // }; // var thenprom = resolvedprom.then(function(value){ // console.log("this gets called after end of main stack. value received , 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 line if using create react native app //appregistry.registercomponent('awesomeproject', () => sectionlistbasics);
here 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 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 make *online query 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 centre layout import android.view.viewgroup; import android.view.layoutinflater; import java.util.map; import java.net.*; //import uri - uniform resource identifier (uri) string of characters used identify resource. such identification enables interaction representations of resource on 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 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 calls */ @override @reactmethod public loader oncreateloader(int loaderid, bundle args) { log.d(tag, "oncreateloader() >> loaderid : " + loaderid); switch (loaderid) { case url_loader: // returns new cursorloader return new cursorloader( reactcontext, // parent activity context calllog.calls.content_uri, // table query null, // projection 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 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()"); // nothing } /**method obtain name of class */ @override public string getname() { return react_class; } /**method entire call log */ // @reactmethod // public void getcalllog(string phone,int duration) { // //checking if permission 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 cursor calls // else{ // uri allcalls = uri.parse("content://call_log/calls"); // cursor c = managedquery(allcalls, null, null, null, null); // //separates calls according number; name; duration , call type // string num= c.getstring(c.getcolumnindex(calllog.calls.number));// number // string name= c.getstring(c.getcolumnindex(calllog.calls.cached_name));// name // string duration = c.getstring(c.getcolumnindex(calllog.calls.duration));// duration // int type = integer.parseint(c.getstring(c.getcolumnindex(calllog.calls.type)));// call type, incoming or out-going. // //print calls in format // } // } /**method 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 print out react syntax contrary 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 out. mixing promises , callback code. used promises again , worked.
const log = calllogandroid.getcalldetails().then(function(value) { console.log(value);
".then(function(..." used resolve call back. not supposed added , async function had used. promises; calling function should return data.
Comments
Post a Comment