Reputation: 383
package com.mohd.tryapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
public static int flag;
TextView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
class getFlag extends AsyncTask<Void, Void, Void> {
private Exception exception;
@Override
protected Void doInBackground(Void... params) {
try{
String url="http://mohdgadi.netai.net/Register.php";
int timeout=15*1000;
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
flag=1;
} catch (Exception e) {
e.printStackTrace();
flag=0;
}
return null;
}
}
}
So this is the code for my main activity i want to connect to my 000webhost website but the connection always shows false.I even tried changing the url to http://mohdgadi.netai.net/Register but that doesnt seem to work what might be the problem because of which the result is always showing false
Upvotes: 0
Views: 46
Reputation: 4702
This is because, if you see the logs, you will notice that your code will throw a NetworkOnMainThreadException. This means that Android doesn't allow you to make a Network call on the main thread. Therefore, move your code into an AsyncTask.
You can see an example here.
You should use get()
to wait for the result to get populated, although it is preferred that you use onPostExecute
to execute your code after doInBackground
returns.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
var.get();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
Upvotes: 2