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.
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.
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.
I have a Web-view In that on click with the help JavaScript interface it will open My android activity's from web-view Here its working fine...
So Here When User Click on any button Which is JS-Interface.. I have added a Alert
So when Ever User click on it... It will show a Dialog...
Now I followed this to add a Option like Don't ask again.... Check box
Here I have given Shared prefs and Check box... But its not working...
and One more thing that check box is viable in web-view... it should show only on alert.. But its showing all time...
Can any one suggest me .. How to Show Alert with Check box.. dont ask again in android Webview... and remember the check box...
java.lang.RuntimeException: Unable to start activity ComponentInfo{Mypackage/myactivity}: android.view.InflateException: Binary XML file line #18: Error inflating class checkbox
Update
Here is my code for that I have added the example code... at alert...
Actually I need a Check Box without XML for Checkbox...(Due to XML for Check box my Main Web-view is Getting some errors)
Is it possible.. If so Let me Know...
I am going to break down your problem into 2 parts
1) Display dialog and remember if user have chosen to not show it again
A simple alert dialog with shared preferences can do that.
private void handleAlertDialog() {
//Handle showAlert
//check if allow to show dialog
if (!getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
.getBoolean("ShowDialog", false)) {
final CharSequence[] items = {"Would like to Remember this setting ? "};
AlertDialog dialog = new AlertDialog.Builder(WebViewActivity.this)
.setTitle("Allow location access")
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
//If the user checked the item, add it to the selected items
// Don't Allow, remember
getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
.edit()
.putBoolean("ShowDialog", true).commit();
Toast.makeText(getApplicationContext(), "Remember", Toast.LENGTH_SHORT).show();
} else {
getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
.edit()
.putBoolean("ShowDialog", false).commit();
Toast.makeText(getApplicationContext(), "Don't Remember", Toast.LENGTH_SHORT).show();
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected item here
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
}).create();
dialog.show();
}
}
2) Trigger this method from javascript.
shouldOverrideUrlLoading(WebView view, String url) is deprecated after Android N show you need to override shouldOverrideUrlLoading(WebView view, WebResourceRequest request) as well.
A complete WebViewClient class will look like this.
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class GeoWebViewClient extends WebViewClient {
Dialog loadingDialog = new Dialog(WebViewActivity.this);
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
} else if (url.startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("showalert:")) {
handleAlertDialog();
} else {
view.loadUrl(url);
}
return true;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
if (uri.toString().startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else if (uri.toString().startsWith("showalert:")) {
//Handle Alert
handleAlertDialog();
} else {
//Handle Web Urls
view.loadUrl(uri.toString());
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webViewPreviousState = PAGE_STARTED;
if (loadingDialog == null || !loadingDialog.isShowing())
loadingDialog = ProgressDialog.show(WebViewActivity.this, "",
"Loading Please Wait", true, true,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do something
}
});
loadingDialog.setCancelable(false);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request,
WebResourceError error) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedError(view, request, error);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceivedHttpError(WebView view,
WebResourceRequest request, WebResourceResponse errorResponse) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedHttpError(view, request, errorResponse);
}
#Override
public void onPageFinished(WebView view, String url) {
if (webViewPreviousState == PAGE_STARTED) {
if (null != loadingDialog) {
loadingDialog.dismiss();
loadingDialog = null;
}
}
}
}
isConnected method is used to check network connection
/**
* Check if there is any connectivity
*
* #return is Device Connected
*/
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm) {
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
return false;
}
As you can see I have added a filter to check for URL start with showalert:. If my Web client class catches any URL starting with showalert then it triggers handleAlert method.
Result
2) Trigger this method from javascript.
shouldOverrideUrlLoading(WebView view, String url) is deprecated after Android N show you need to override shouldOverrideUrlLoading(WebView view, WebResourceRequest request) as well.
A complete WebViewClient class will look like this.
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class GeoWebViewClient extends WebViewClient {
Dialog loadingDialog = new Dialog(WebViewActivity.this);
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
} else if (url.startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("showalert:")) {
handleAlertDialog();
} else {
view.loadUrl(url);
}
return true;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
if (uri.toString().startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else if (uri.toString().startsWith("showalert:")) {
//Handle Alert
handleAlertDialog();
} else {
//Handle Web Urls
view.loadUrl(uri.toString());
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webViewPreviousState = PAGE_STARTED;
if (loadingDialog == null || !loadingDialog.isShowing())
loadingDialog = ProgressDialog.show(WebViewActivity.this, "",
"Loading Please Wait", true, true,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do something
}
});
loadingDialog.setCancelable(false);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request,
WebResourceError error) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedError(view, request, error);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceivedHttpError(WebView view,
WebResourceRequest request, WebResourceResponse errorResponse) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedHttpError(view, request, errorResponse);
}
#Override
public void onPageFinished(WebView view, String url) {
if (webViewPreviousState == PAGE_STARTED) {
if (null != loadingDialog) {
loadingDialog.dismiss();
loadingDialog = null;
}
}
}
}
isConnected method is used to check network connection
/**
* Check if there is any connectivity
*
* #return is Device Connected
*/
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm) {
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
return false;
}
As you can see I have added a filter to check for URL start with showalert:. If my Web client class catches any URL starting with showalert then it triggers handleAlert method.
Result
I have one app .When click submit ==> my webpage will show result .But i don't know use javascript json.anyone help me.thank you very much
Sorry.I have litte Eng..so..
==>It my app android
==>It's my webpage (image and code)
<html>
<head>
<script>
function myFunction() {
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
Code java (my app)
public class ChennaiIntent extends Activity implements OnClickListener{
private EditText value;
private Button btn;
private ProgressBar pb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
value=(EditText)findViewById(R.id.editText1);
btn=(Button)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(value.getText().toString().length()<1){
// out of range
Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(value.getText().toString());
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://11.10.88.2/tuan/example.html");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}