react-native-document-picker not returning anything - javascript

Idk whether this is because of the react native version or something else make this happen. So I've just integrating my android app with React Native and migrating to AndroidX. Before I did the integration and migration, this code is perfectly fine, I get the result and everything. But, after the integration and migration, I can only see and click the photo from the image list, there's no result, console.log() does not working, and even I don't get any error on catch block
I'm using react-native-document-picker from https://github.com/Elyx0/react-native-document-picker and React Native 0.60.5
I've tried using this different library https://www.npmjs.com/package/react-native-file-picker, but the issue is same
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.images],
});
console.log(res) //not showing anything
if (res.size <= 3145728) {// 3 MB
dispatch({
type: ACTION_TYPE_PICK_PHOTO_PROFILE_SUCCESS,
payload: res,
});
} else {
dispatch({
type: ACTION_TYPE_PICK_PHOTO_PROFILE_EXCEED,
payload: res
});
}
} catch (err) {
console.log(err) //not showing anything
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
}
}
Any help would be great! Thanks in advance.

Solved. Turns out I forgot to add the function for onActivityResult. This is the code that I used.
private final int OVERLAY_PERMISSION_REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SoLoader.init(this,false);
mReactRootView = new RNGestureHandlerEnabledRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setCurrentActivity(this)
.setBundleAssetName("index.android.bundle")
.setJSMainModulePath("index")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
} else {
startReactNative();
}
}
private void startReactNative() {
// The string here (e.g. "MyReactNativeApp") has to match
// the string in AppRegistry.registerComponent() in index.js
mReactRootView.startReactApplication(mReactInstanceManager, "NusaTalent", null);
setContentView(mReactRootView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Log.e(TAG, "onActivityResult: SYSTEM_ALERT_WINDOW permission not granted");
} else {
startReactNative();
}
}
}
Log.d(TAG, "onActivityResult: " + data);
mReactInstanceManager.onActivityResult( this, requestCode, resultCode, data );
}

Thanks a lot #arthur-bachtiar for your solution, all that was required for it to work was this on my case:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
...
}
I find really disapointing that to the present day the mantainers of the library have not clarify this existing issue on the repository, nor include any working examples or instructions on the installation steps for this procedure.

Related

Andorid Studio (Volley ) JsonObjectRequest

I tried everything to get data through a query with the JsonObjectRequest and it doesn't bring me any information, the query is well done, I just don't know why it doesn't bring me the data
public void ViewDate(View view){
String get_id= ID.getText().toString().trim();
String url="http://192.165.0.196/android_msyql/consultar.php?id"+get_id;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String nametxt, emailtxt;
try {
nametxt = (String) response.get("name");
emailtxt = (String) response.get("email");
nombre.setText(nametxt);
email.setText(emailtxt);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this," NOTHING",Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonObjectRequest);
}
Before making a request, the site must be on the Internet.
You check the link with the browser, if the browser fails to show the site then you will not get any response.

WebSockets fails to connect because of lost connection

I'm using spring boot in my backend and vuejs in my front-end . I've defined everything in the guide yet I still don't get my project to work.
FrontEnd
connectToWS() {
this.socket = new Sock("http://localhost:8754/stomp-endpoint");
this.stompClient = Stomp.over(this.socket);
this.stompClient.connect(
{},
frame => {
this.connected = true;
console.log(frame);
this.stompClient.subscribe("/topic/greetings", tick => {
console.log(tick);
this.received_messages.push(JSON.parse(tick.body).content);
});
},
error => {
console.log(error);
this.connected = false;
}
);
},
Backend
WebSocketConfiguration Class :
#Configuration
#EnableWebSocketMessageBroker
public class WebsocketConfiguration implements
WebSocketMessageBrokerConfigurer
{
#Override
public void registerStompEndpoints(StompEndpointRegistry registry)
{
// with sockjs
registry.addEndpoint("/stomp-endpoint")
.setAllowedOrigins("http://localhost:8081")
.withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes("/app")
.enableSimpleBroker("/topic");
}
}
WebSecurityConfigClass :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/api/v*/registration/**").permitAll()
.antMatchers("/topic**").permitAll()
.antMatchers("/stomp-endpoint").permitAll()
UPDATE :
The error is actually coming out from the browser . It actually changes the route of the api because it has sockjs integrated into it. I couldn't figure out why the API always gets a /info?t=RandomNumber after it. I need the route to remain the same as I typed it in the front-end.
How can I stop the browser from updating my path. Thanks for helping !

Events not being sent to JavaScript

I am using react-native to develop an android app. I am using native code to run a service in the foreground. This service consists of collections the accelerometer sensor readings of the phone.
Starting the service returns a successful promise but I do not receive no events. The following is the implementation of the service class:
public class PhonePositionService extends Service {
public static final String FOREGROUND = "com.testnative.position.FOREGROUND";
...
//Event listener for sensors -start
SensorEventListener sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
PhonePositionService.this.sendMessage(event);
}
...
};
//Event Listener - end
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onCreate() {
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); //get services provided by sensor manager
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); //specifiy sensor
sensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); //register it
}
private void sendMessage(SensorEvent event) {
try {
float[] values = event.values;
Intent intent = new Intent("PhonePosUpdate");
intent.putExtra("message", values);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
...
The thing is not even a notification appears, I'm afraid the service didnt start at all.
The Following is my Module which uses this service:
public class PhonePositionModule extends ReactContextBaseJavaModule {
public PhonePositionModule(ReactApplicationContext reactContext) {
super(reactContext);
BroadcastReceiver phonePositionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float[] message = intent.getFloatArrayExtra("message");
PhonePositionModule.this.sendEvent(message);
}
};
LocalBroadcastManager.getInstance(getReactApplicationContext()).registerReceiver(phonePositionReceiver, new IntentFilter("PhonePosUpdate"));
}
...
#ReactMethod
public void startService(Promise promise) {
String result = "Success";
try {
Intent intent = new Intent(PhonePositionService.FOREGROUND); ///////
intent.setClass(this.getReactApplicationContext(), PhonePositionService.class);
getReactApplicationContext().startService(intent);
} catch (Exception e) {
promise.reject(e);
return;
}
promise.resolve(result);
}
...
private void sendEvent(float[] message) {
WritableMap map = Arguments.createMap();
map.putDouble("x", message[0]);
map.putDouble("y", message[1]);
map.putDouble("z", message[2]);
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("updatePosition", map);
}
}
When I call startService() from JavaScript, I get a success. However no notification appears and
DeviceEventEmitter.addListener('updatePosition', (Data) => {
console.log(Data);
in App.js shows nothing.
Thus:
1) The Notification does not appear
2) Given that the notification does not appear, the service did not start (even though the promise did not return an error).
I tried debugging the native code on Android Studio but logcat isn't working for me.

how to pass the callback function in node.js from android client

I want to send data from socket in android client to node.js server ..
what ive done in server side :
socket.on('new user',function(data,callback){
console.log('ON new user');
if(data in users ){
callback(false);
}else {
callback(true);
socket.nickname = data;
users[socket.nickname]= socket;
UpdateNickNames();
}
});
and on my client android :
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
EditText edt;
Button btn;
boolean msg;
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.1.101/");
Log.v(TAG,"fine");
} catch (URISyntaxException e) {
Log.v(TAG,"Error..... "+e.getMessage());
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSocket.connect();
edt=(EditText)findViewById(R.id.editText);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptSend();
}
});
}
private void attemptSend() {
String message = edt.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
mSocket.emit("new user", message, true);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
but it's crash with error :
throw er; // Unhandled 'error' event ^ TypeError: callback is not a function
I believe your server-side code looks good. the problem is on the clientside... when you are emiting the "new user" event, make sure its a function you are passing as a parameter, instead you passed a boolean value(true). Try this,
mSocket.emit("new user", message, callback);
Also, based on the callback result you get from serverSide, you do something, else you do something else..
HOPE THIS HELPS!
I've found The Solution here :
mSocket.emit("new user", message, new Ack() {
#Override
public void call(Object... args) {
//Code goes here
}
});
}

how to properly open google play links on html page in android webview with setWebViewClient?

Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it out so i'll explain in deep detail...Any help would be much appreciated!!!
i have a webpage at http://s-ka-paidbeats.com/app_tree/ourotherapps it lists a bunch of apps i have made in google play.in the webpage html i have them listed with standard links like - https://play.google.com/store/apps/details?id=com.yesorno.app.yesorno
i've created a tab in ALL the android applaications that i've made called "My Other Apps"this tab is a webview window that shows the same html page i was talking about above- http://s-ka-paidbeats.com/app_tree/ourotherapps
the problem is when a user visits the webview window in any of my android applications and clicks on any of the apps i have listed on the html webpage (https://play.google.com/store/apps/details?id=) it takes them to google play in the webview window and asks them to login to google play in the webview window (even if they are already logged in to google play on their device)... this is extremely ugly and annoying for users to face.
i want to make it so when a user visits the "my other apps" tab in any of my applications, and clicks on one of the apps in the webview window it opens the actual google play application (if google play is installed) or opens in the default browser installed on the device (if google play is not installed)
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page and then visited the webview window again in my app however this time when i click on any of the apps listed i just get a page error "page does not exist" window
i have looked into setWebViewClient and i am sure that there is someway to do this using something like the code posted below
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getScheme().equals("market")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("http://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
} });
I tried adding the code above to my current code but now my loading dialog box wont close when the webview is loading.... it just stays loading forever.... so i took the code snippet above out of my code again because i dont think i am placing it in the right place or that i am integrating the two codes together properly....
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one....... I HAVE NO CLUE where to begin and i have been reading for hours....
Here is my current code
package com.yesorno.app.yesorno;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.yesorno.app.yesorno.NetorkConnection;
#SuppressLint("SetJavaScriptEnabled")
public class OtherApps extends AppCompatActivity {
private WebView webView;
NetorkConnection ntwrk_con = new NetorkConnection(this);
ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toolsresources5 = (TextView)findViewById(R.id.feedbacktextview);
toolsresources5.setVisibility(View.INVISIBLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.activity_main_webview);
dialog = new ProgressDialog(OtherApps.this);
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
dialog_box_for_internet();
}
}
public void dialog_box_for_internet() {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
// dismis_dialog_box_for_internet = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
OtherApps.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_custom_titile, null);
TextView title = (TextView) view.findViewById(R.id.myTitle);
title.setText("Unable To Connect");
builder.setCustomTitle(view);
builder.setMessage("No Internet Connection")
.setCancelable(false)
.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
new Thread_for_internet().execute();
}
// dialog.cancel();
}
})
.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
// Gridview.super.onBackPressed();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
class Thread_for_internet extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading..Please wait.");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
dialog_box_for_internet();
}
}
public void webView() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
dialog.setMessage("Loading All Our Apps...\nPlease wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
webView.loadUrl("http://s-ka-paidbeats.com/app_tree/ourotherapps.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean bRet=false;//set true is menu selection handled
switch (item.getItemId()) {
case R.id.action_settings_3:
Toast.makeText(this, Html.fromHtml("<big><b>Develeped By S-Ka-Paid</b></big><br>© 2016 S-Ka-Paid"), Toast.LENGTH_LONG).show();
bRet=true;
break;
case R.id.action_settings_4:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent2.setData(Uri.parse("market://details?id=com.yesorno.app.yesorno"));
startActivity(intent2);
bRet=true;
break;
default:
bRet=super.onOptionsItemSelected(item);
}
return bRet;
} }
Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it outAny help would be much appreciated!!!
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page
Don't do that. Use the google play URLs you started with.
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one
You combine them. You create one WebViewClient to handle all the needs of one WebView. It's not difficult:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});
for anyone looking for the answer to this... here is the correct code
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});

Categories

Resources