Andorid Studio (Volley ) JsonObjectRequest - javascript

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.

Related

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
}
});
}

Android Alert with "Don't show again" checkbox in Webview

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

Window cancel in jsp. How to return to previous page. JS

My class controller in JAVA:
public class Controller extends HttpServlet {
private Chooser chooser = Chooser.INSTANCE;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
try {
String page = chooser.chooseCommand(req.getParameter("command")).execute(req, resp);
req.getRequestDispatcher(page).forward(req, resp);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
}
}
Next, class ENUM, that choose page:
public enum Chooser {
INSTANCE;
private Map<String, ICommand> commandMap = new HashMap<>();
private Chooser() {
// commands for profession
commandMap.put("professions", new ProfessionCommand());
commandMap.put("addProfession", new AddProfessionCommand());
commandMap.put("saveProfession", new SaveProfessionCommand());
commandMap.put("deleteProfession", new DeleteProfessionCommand());
commandMap.put("editProfession", new EditProfessionCommand());
public ICommand chooseCommand(String command) {
return commandMap.get(command);
}
}
Interface, icommand:
public interface ICommand {
String execute(HttpServletRequest request, HttpServletResponse resp);
}
My class DeleteProfessionCommand:
public class DeleteProfessionCommand implements ICommand {
private ApplicantDBProvider provider = ApplicantDBProvider.INSTANCE;
#Override
public String execute(HttpServletRequest request, HttpServletResponse resp) {
try {
Long professionId = Long.parseLong(request.getParameter("id"));
provider.deleteProfession(professionId);
} catch (Exception e) {
request.setAttribute("error", e);
return "pages/error.jsp";
}
return "controller?command=professions";
}
}
In my jsp, when i want to delete row, i used this command:
Delete
My question:
When, i click delete, i want to get allert message, that tell me:
"Are you sure to delete", and buttons, "Yes", "No".
How to do this, i dont know. Because, i learn only java, and no more month .
Please help. Thanks.
You can achieve that with javascript, in your jsp the anchor tag for Delete
Delete
make these changes,
<a class="deleteAnchor" data-command="deleteProfession" data-id="${profession.getId()}" href="javascript:void(0);">Delete</a>
Then, add the below at the end of the your jsp,
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript">
$('.deleteAnchor').on('click', function(){
// confirm will give you a 'ok' and 'cancel' button instead of yes or no
// you can use one of the other libraries like bootbox to get a nice confirmation dialog box with 'yes' and 'no' buttons
var result = confirm('Are you sure to delete?');
if(result) {
//Delete
$.ajax({
url: 'controller',
data: {'command' : $(this).data('command'), 'id' : $(this).data('id')},
success: function() {
//Do something on success
}
});
} else {
//Dont delete
}
});
</script>
You can refer bootbox for better confirmation boxes

Running JavaScript in WebView with LoadData after getting data from post request

I want to run javascript in android in webview with loadData method of webview, after getting html in string form through a post request. Here is my code. I have searched many links but no one was according to my scenario. Any help?
public class MainActivity extends ActionBarActivity {
WebView wv;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv=(WebView)findViewById(R.id.webView1);
Thread t= new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
postData();
}
});
t.start();
while(t.isAlive());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadData(result, "text/html", null);
}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://result.abc.com/Home1/R2");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("value1", "5001"));
nameValuePairs.add(new BasicNameValuePair("value2", "201214"));
nameValuePairs.add(new BasicNameValuePair("value3", "212"));
nameValuePairs.add(new BasicNameValuePair("value4", "ABC"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
you place this two line of code after getting result of the post request.
wv.getSettings().setJavaScriptEnabled(true);
wv.loadData(result, "text/html", null);
after result = EntityUtils.toString(response.getEntity());
so, final code look like this ::
result = EntityUtils.toString(response.getEntity());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadData(result, "text/html", null);

Categories

Resources