getjson response returns null in phonegap (android) - android

$.getJSON("http://localhost:8080/v1/message",
function(data) {
console.log(data);
alert("message"+data);//this alert stmt is displayed it means that
the service call is getting executed
});
service method
#RequestMapping(method = RequestMethod.GET,
value = "/message" )
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public String message()
{
return "jasdknsd";
}
I am getting response of this call as null please help me out if I am doing something wrong in the service method and I have both of them in same network because of which I am not using callback

Connection to localhost is not supported.
http://code.google.com/p/android/issues/detail?id=133
127.0.0.1 is the emulated system's own loopback interface, not the one running on
your host development machine.
within the Android system, one should use 10.0.2.2 which is an alias specifically
setup to contact your host 127.0.0.1

use 10.0.2.2 instead of localhost:8080

Related

Unable to return IP address using react-native-device-info's getIPAddress()

I need to return the IP address for the device running my React Native app (an Android smart tv app). I am making use of react-native-device-info which has allowed me to get the model, manufacturer and operating system. However I am unable to get the ip address.
This is my code
deviceInfo = DeviceInfo.getIPAddress().then(ip => {
return ip;
});
However on the front end it appears as [object Object]. I can see in the console it is returning an object like this:
wifi:
_40: 0
_55: null
_65: 0
_72: null
I would have hoped to just return a string of the correct IP address.
I have also added the right permissions in my AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Also worth noting I am passing the information back by value: ${JSON.stringify(deviceInfo)}
Any one experienced this issue before?
I have used below library:
https://www.npmjs.com/package/react-native-network-info
And it is working fine, Below is the code:
// Get IPv4 IP (priority: WiFi first, cellular second)
NetworkInfo.getIPV4Address().then(ipv4Address => {
console.log(ipv4Address); //result e.g 192.168.1.100
});
Since its returning a promise try putting inside a async function and try to get the result.
Ex:
const getIpAddress = async()=>{
const ip = await DeviceInfo.getIPAddress();
console.log(ip);
return ip;
}
Hope it helps. Thank you.

error in connecting to the server

I created a database on cpanel and i choosed a name and pass for it.
So i declared "database","password","user name","localhost" in services.php.
Services.php:
<?php
if (isset($_REQUEST['action'])){
$foo = $_REQUEST['action'];
}else{
echo "Invalid Data";
exit;
}
/*************************************************/
function connectToDatabase()
{
$servername ="localhost";
$username = "us_utab";
$password = "sk3%CkvH";
$dbname = "us_utab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
/*************************************************/
if ($foo == 'search')
{ search(); }
if ($foo == 'read')
{ read();}
if ($foo == 'insert')
{ insert();}
.
.
.
I changed my android code.
HttpPost method = new HttpPost("http://192.168.1.2/test-website/services.php?action=read");
To :
HttpPost method = new HttpPost("https://utab.com:2083/services.php?
action=read");
Is this correct?
It is not need to use database name , password , user name in android place?
It does not connect to server . so I deleted port 2083 and I am encountering error in below :
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
Well your code seems to be correct and not the problem in this case.
It is not need to use database name , password , user name in android place?
Nope you don't have to if the PHP file already contains these values.
The actual error we are seeing is a SSLPeerUnverifiedException which means that the Certificate of https://utab.com has some issues. So you need to check on that. Also check the date of your device, is it correct?
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
That means you are trying to do a secure https connection to a http server that doesn't expect for secure connections.
$servername ="localhost";
$username = "us_utab";
$password = "sk3%CkvH";
$dbname = "us_utab";
Is that the only contents of services.php ? If yes then it lacks all the code to connect to the database, get arguments from the http request, make probably some database query and return some response. It seems that if the only one argument is action=read it is not clear what it must respond.
UPDATE
After reading your comment, if the server is accessible from the same computer but not from another computer then you have an IP routing problem, not a programming problem. May the computer on the server resides has a firewall that blocks incoming connections, or its network interface is misconfigured.
Take also in account that inside a LAN the public IP with which the router connects to the WAN is not accessible from the LAN computers. For testing inside the LAN you have to use the private LAN IPs, for example 192.168.1.2, not "utab.com"

failed to connect to localhost/127.0.0.1 android

I am new to android development, and trying to call local .NET web api service in android via retrofit library. After starting my web api on IIS I am getting this error failed to connect to localhost/127.0.0.1 android.
When I did same thing as suggested http://themakeinfo.com/2015/04/retrofit-android-tutorial/, It's working fine, But my localhost service is not calling up from android
My service url is,
http://localhost:52511/api/Values/getAllStudents/5
and it is giving me output in XML format in browser too.
I have also try to call it with,
public interface gitapi {
#GET("/api/Values/GetProduct/{id}") //here is the other url part.best way is to start using /
public void getFeed(#Path("id") int id, Callback<gitmodel> response);
}
public class gitmodel {
public int studentId;
public String studentName;
public String studentAddress;
}
String API = "http://10.0.2.2:52511";
public void CallService(View view){
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API).build();
gitapi git = restAdapter.create(gitapi.class);
int id = 5;
git.getFeed(id, new Callback<gitmodel>() {
#Override
public void success(gitmodel gitmodel, Response response) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), "Errors", Toast.LENGTH_LONG).show();
}
});
}
but no luck.
Please tell me where do I need to change to make it work. ?
Response I am getting in browser is,
<ArrayOfstudents xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/APICall.Controllers">
<students>
<studentAddress>valsad</studentAddress>
<studentId>1</studentId>
<studentName>Keval</studentName>
</students>
<students>
<studentAddress>Hyderabad</studentAddress>
<studentId>2</studentId>
<studentName>Honey</studentName>
</students>
</ArrayOfstudents>
Instead of using 127.0.0.1:<PORT> use your local IP
There's nothing to do with retrofit library in your case.
It's about your network settings,
your phone and IIS server must be the same LAN.
You can follow as below.
Launch an AP on you IIS server;
Connecting the AP with your phone.
Sometimes you need to close security firewall on your IIS server.
I had the same problem as u (failed to connect to localhost/127.0.0.1).
First of all i recommend u to read this:
android developer's guide (main part of this on the image↓)
I had all of this, mean A, B and C. As C(emulator) i used a Genymotion.
And i solved my problem by changing Network Configurations on it.
IMPORTANT: my adress in baseURL were: "localhost:8099/"
Let's see it:
U should click on Settings → Network → check Use HTTP Proxy → input your IP adress and Port(in my situation it was 8099) → close. See it more details on image ↓
I have the same problem, and I resolve it by changing the IP address instead of 'localhost':
open cmd(if you are using windows): type 'ipconfig' and see your computer's ip.(make sure that your computer and your android device connect to the same network).
remove 'localhost' in the url and use the ip(ip of your computer in step 1).
run the project again and check
Actually this helped when using 2 apps on the same Android device (Android 9)
android:usesCleartextTraffic="true"
You can try this in androidmanifest.xml
android:usesCleartextTraffic="true"

Proper way to call a REST service in Phonegap

I've taken an AngularJS web page that is able to call my REST service using GET, and put this code into my Android/Phonegap project and the rest service isn't called.
so this code below works standalone but not within phone application
$http.get('http://localhost:40884/api/sampleapi/get').success(function (data) {
alert("cool");
$scope.posts = data;
$scope.loading = false;
})
.error(function (request, status, error) {
alert("err");
console.log(data);
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
I've checked the manifest has
and the res/config.xml file has
<access origin="*"/> <!-- allow local pages -->
But these haven't made a difference. Trying to trace out the request,status,error variables only retrieve a 0 for the error variable.
Any ideas about what to try here appreciated
Cheers
M
I believe localhost is your computer, and since your phone or emulator is a different machine, you need to replace localhost with your computer's local ip address(something like 192.168.1.10). Later when you want to make it work even on different networks you need to put your api online(like a hosting)
I suggest that you assign a static local ip to your computer and use that address instead of localhost all the time.

Challenge with Android communicating to GAE using restlet

I'm using Eclipse to (try to) build an Android client to get reuse a restlet service I developed using GAE and GWT.
My service is running at
http://127.0.0.1:8888/abc/audits
I can test this by going directly to this url, and by using my GWT client - both work.
However, the following code returns a communication error
private AuditsResource resource;
private Audits audits;
ClientResource cr = new ClientResource("http://127.0.0.1:8888/abc/audits");
resource = cr.wrap(AuditsResource.class);
try {
// Get the remote contact
audits = resource.retrieve();
// The task is over, let the parent conclude.
handler.sendEmptyMessage(0);
} catch (Exception e) {
Message msg = Message.obtain(handler, 2);
Bundle data = new Bundle();
data.putString("msg", "Cannot get the contact due to: "
+ e.getMessage());
msg.setData(data);
handler.sendMessage(msg);
}
I have no idea where to look next. I've instrumented the server implementation of AuditsResource, and it is never touched (by the Android application).
The AuditsResource class has one method, to keep things simple for now
#Get
public Audits retrieve();
It appears the problem is that the Andriod Emulator cannot connect to either 127.0.0.1 or 10.0.2.2. The solution is to use your PC's IP address.
I am able to connect from Android to my local Google App Engine through Android/Restlet using 10.0.2.2 instead of localhost.

Categories

Resources