Android app can't post to url - android

I'm working on a relatively simple login app for a school project. I'm having an issue connecting my app to any URL, local or otherwise. I've added the permission for internet access to the android manifest file.
<uses-permission android:name="android.permission.INTERNET" />
The following code is located in my main activity:
public class MainActivity extends Activity {
private EditText username=null;
private EditText password=null;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.ucidText);
password = (EditText)findViewById(R.id.passText);
login = (Button)findViewById(R.id.button1);
//URL CAN BE ANYTHING, WOULD NORMALLY BE 192.168.1.102
if(isConnectedToServer("<-URL to page on locally hosted server->",10)){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Connection failed", Toast.LENGTH_SHORT).show();
}
}
//Function to determine if connection exists
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url); //<--------- I believe the issue has to do with this line.
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}
}
This is a stripped down version of my overall project. Everything checks out except the connectivity. I'm running the app from the SDK straight on my phone (Moto X). Any suggestions?

You got the android.os.NetworkOnMainThreadException because you perform your network request on the main thread. You should not do that because you will block the main thread. Instead, you can start a new thread to perform your network request, like this:
final Handler handler = new Handler();
new Thread(){
public void run(){
// check network connection here.
handler.post(/* do the toast work in a Runnable as the parameter here*/);
}
}.start();

You should use some protocol in the "url" string.
For example, you can use
"http://serverIP"
in which the serverIP is 192.168.1.102 and the port is default to 80.
We could not use "192.168.1.102" as the url because the protocol could not be ignored for the URL class.

Related

I am getting an error connecting to IP (Socket failed: EPERM)

I have trouble with connecting to a local web interface (192.168.10.13:3671) that are connected to my KNX network from the emulator/phone in Android Studio.
I've tried to connect to the same web interface with a already developed app called KNXwizard and that works, but I see in the code that that app uses AsyncTask.
Always getting this error: Error creating KNXnet/IP tunneling link: tuwien.auto.calimero.KNXException: connecting from /192.168.163.198:3671 to /192.168.10.13:3671: socket failed: EPERM (Operation not permitted)
I've checked this posts
Socket failed 1
Socket failed 2
Tried everything there, added permissions to my AndroidManifest.xml, uninstalled, used physical phone etc. But nothing works.
It could be my code, I've tried searching for an alternative method for AsyncTask. So it could be that the code is written wrong. Hope someone could help me out.
MainActivity:
public class MainActivity extends AppCompatActivity {
private static InetSocketAddress local = new InetSocketAddress("192.168.163.198", 3671);
private static InetSocketAddress server = new InetSocketAddress("192.168.10.13",
KNXnetIPConnection.DEFAULT_PORT);
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
ExecutorService executorService = Executors.newSingleThreadExecutor();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executorService.execute(new Runnable() {
#Override
public void run() {
//doInBackground
System.out.println("This example establishes a tunneling connection to the KNXnet/IP server " + server);
// A KNX tunneling link supports NAT (Network Address Translation) if required.
// We also indicate that the KNX installation uses twisted-pair (TP) medium, with TP1 being the most common.
// KNXNetworkLink is the base interface implemented by all supported Calimero links to a KNX network.
try (KNXNetworkLink knxLink = KNXNetworkLinkIP.newTunnelingLink(local, server, false, TPSettings.TP1)) {
System.out.println("Connection established to server " + knxLink.getName());
System.out.println("Close connection again");
} catch (KNXException | InterruptedException e) {
// KNXException: all Calimero-specific checked exceptions are subtypes of KNXException
// InterruptedException: longer tasks that might block are interruptible, e.g., connection procedures. In
// such case, an instance of InterruptedException is thrown.
// If a task got interrupted, Calimero will clean up its internal state and resources accordingly.
// Any deviation of such behavior, e.g., where not feasible, is documented in the Calimero API.
System.out.println("Error creating KNXnet/IP tunneling link: " + e);
}
}
});
}
});
}
I figured it out.
It was a stupid mistake with the IP address, should have seen that before. I just change the IP address to that I have on the phone I was connected to (192.168.10.15).

Unable to send GET request to a url in android?

I am currently new to android programming but I recently created a rest api using slim library that takes a GET request and adds it to the database it's parameters but I don't know how to send it inside android app.
here is my code:
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try
{
URLConnection myURLConnection=null;
URL myURL=null;
String mainUrl="http://107.170.31.137/StudentApp/v1/garden/name2/user2/pass2";
myURL = new URL(mainUrl);
myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "in catch", Toast.LENGTH_LONG).show();
}
}
});
I even added the permissions :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
still the app is not working. am i doing something wrong? please help. also, I want to change the GET parameters every time to the new variables I get from somewhere else how can i do that?
For Network Relational Operations Make Use of the following Libraries(Asyntask)
Retrofit (Recommended)
Okhttp
Volley
Check my Example Project on Retrofit

Connect a client app Android to a server written with Sails.js using socket.io

Here's my situation: i have a server written with sails.js where i have a user model. I have a dashboard where i can see all the users, create new, delete them and so on...Now i want to create an android app where i can get, using socket.io, notification about the events that occour to the user model.
Example: if i delete a user from my dashboard i want the app to recive a notification from the server that the user has been deleted.
Here's my code for the app:
public class MainActivity extends Activity {
//socket instance
private Socket mSocket;
{
try {
mSocket = IO.socket("http://server_url:port/user");
} catch (URISyntaxException e) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //set the layout for this activity
final TextView tv = (TextView) findViewById(R.id.textView);
mSocket.on("user", new Emitter.Listener() {
#Override
public void call(Object... args) {
tv.setVisibility(View.INVISIBLE);
}
});
mSocket.connect();
final Button btn_createUser = (Button)findViewById(R.id.button);
btn_createUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSocket.connected()) {
//tv.setVisibility(View.INVISIBLE);
}
}
});
}
}
Like i did with the dashboard to connect the socket to the server i did the same thing here, but it seems like the socket doesn't connect, in fact, when i delete a user from the dashboard i get no notification.
Here's the code (that works) i used in my dashboard to connect my socket to the server and listen to updates from the user model:
//connect to the server and listen to updates from user model
io.socket.get('/user', function(data, jwres) {
$scope.users = data;
$scope.$apply(); //write users in the table...
});
//wait for updates...
io.socket.on('user', function serverResponded (data) {
if(data.verb == "updated")
{
//get the user index in the array and update it
var index = getIndex(data.id, $scope.users);
$scope.users[index].online = data.data.online;
$scope.$apply();
}
if(data.verb == "destroyed")
{
//get the user index in the array and remove it
var index = getIndex(data.id, $scope.users);
$scope.users.splice(index, 1);
$scope.$apply();
}
if(data.verb == "created")
{
//simply update the array
$scope.users.push(data.data);
$scope.$apply();
}
});
Now, i think all i'm missing out in the android app is the GET request which automatically subscribe my socket to the model and get notified if something happen...but i don't know hot to do it.
I hope i was clear enough...thank to everyone who will answer me!
PS: i don't want to use AndroidAsync because i need the ultimate version of socket.io!
In case someone need it, i found the solution: https://github.com/balderdashy/sails/issues/2640 here you can find out how to solve the issue! :)

Android/Java: How do i implement AsyncTask?

I've made an app that sends a request to a webserver in a specified interval and gets XML data. It then parses the XML data, gets information from the phone (text messages, contacts or something similar) and shoots it back to the server with a http post request.
The problem is that it usually takes a few seconds for the app to get the info, which often leaves the app crashing. A dialog comes up saying the app has become unresponsive and asks if i want to close the app or wait, if i press wait it eventually starts working again.
Is AsyncTask the right solution to this problem?
Another thing i don't really understand is how AsyncTask actually works. Let's say i have two methods that do a lot of work and crashes the app, can i put both of them in one AsyncTask and just call them from doInBackground()?
I have also implemented something similar you are trying. That is sending request to server, receive XML response, parse XML, show result. View This. I have used AsyncTask for this.
Here is how i have implemented it using AsynTask
private class AsyncClass extends AsyncTask<Void, Void, Bundle>{
#Override
protected Bundle doInBackground(Void... arg0) {
Bundle b=startProcess();
// startBundle() method do all the processing and return result in a bundle. You can as many methods from within startBundle() method
return b;
}
#Override
protected void onPostExecute(Bundle result) {
Log.d(TAG , "In onPostExecute");
dialog.dismiss();
if(result==null)
Toast.makeText(cont, "Can't process query.\nTry again later.", Toast.LENGTH_LONG).show();
else{
Intent in = new Intent(cont, QueryResultDisplay.class);
Log.d(TAG , "Displaying");
in.putExtras(result);
cont.startActivity(in);
}
}
I give you brief description about your problem.
There are many possibility that you don't get data from server
if your network speed is very slow and you try to get all the
information from server and XML data then in this case if network crash then it show you error
if you're making request to that page which is not in server
Now, if you are facing the problem in code, then I give you the complete code of AsyncTask class which I had implemented in my project and it work fine.
private class GetLoginResponse extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
private String email;
private String password;
public GetLoginResponse(String emailId, String paswd) {
this.email = emailId;
this.password = paswd;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(LoginActivity.this, "",
"Loading....", true, false);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
//here u can check the reponse is ok and 200
} catch (NetworkException e) {
isNetworkError = true;
}
return false;
}
#Override
protected void onPostExecute(Boolean data) {
progressDialog.dismiss();
System.out.println("lOGIN RESPONSE for email = " + email + data);
}
}// end AsyncTask
This would solve your problem.
Yes, you can use AsyncTask.
The code called in doInBackground() must not touch the UI.
You can touch the UI thread with publishProgress().

VPN connection from Android emulator fails

I am new to Android development. I am trying to join an existing VPN from my Android app. I want to integrate the VPN in my app; my app then is supposed to query a remote database.
I got some code and tried to use it to create a VPN. It emulates the built-in VPN manager on the Android phone. The code compiles and the manager is launched but the connection to the VPN does not succeed when I try to connect after all configuration. The protocol is PPTP. A VPN exists and has been tested.
I tried connecting from an android phone with the same settings and it was successful.
I thought maybe I am passing the parameters in the wrong way. I have put the code for the vpn part below. The url is not the actual but in same format.
Any help to identify what I am doing wrong would be appreciated. Also if there is a way I can directly call the VPN manager from my app.
Thanks very much for any help,
final Button button1 = (Button)findViewById(R.id.button1);
final Button button2 = (Button)findViewById(R.id.button2);
final Button button3 = (Button)findViewById(R.id.button3);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent("android.net.vpn.SETTINGS"));
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url = null;
try {
String registrationUrl = String.format("daffy.zune.org");
url = new URL(registrationUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("MyApp", "Registration success");
} else {
Log.w("MyApp", "Registration failed for: " + registrationUrl);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.register);
}
});
}
}
I suggest you look at the simplevpn project and browse the source here and view ShowAllVPNsActivity.java.
Hope this helps! We need more good VPN apps in the Market!

Categories

Resources