Android App figure out whether there is an connection - java

i want to ask a question which may is very simple for some of you.
How can i figure out, whether my Application has an internet connection?
I want to connect to an MySQL Database and when there is no Internet, there should be an AlertDialog.
new AsyncTask() {
ProgressDialog dialog = ProgressDialog.show(AppActivity.this, "Lade", "Daten werden abgerufen...", true);
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
max = Name.size()-1;
kontrolle = new boolean [max*2];
pb.setMax(max/2);
java.util.Arrays.fill(kontrolle, false);
bilder();
}
#Override
protected Object doInBackground(Object... arg0)
{
// TODO Auto-generated method stub
dialog.show();
getData();
return null;
}
}.execute();
private void getData()
{
String result = "";
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://.../read.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = "";
while((line= reader.readLine())!=null)
{
sb.append(line+"n");
}
is.close();
result = sb.toString();
result.trim();
}
catch(Exception e)
{
Log.e("log-tag","Error"+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
ID.add((String) json_data.get("id"));
Name.add((String) json_data.get("name"));
Pts.add((String)json_data.get("pts"));
}
}
catch(Exception e)
{
Log.e("log-tag","Error2"+e.toString());
}
}
How can i achieve that? i have no idea
i thought this
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
would do the work, but when i have no connection (because i set my phone in flight mode) there is just an endless ProgressDialog :(

As Jon Taylor mentioned this is a duplicate question
you can use the following code to do this
this method checks whether mobile is connected to internet and returns true if connected and displays an alert box if not:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
AlertDialog.Builder altDialog= new AlertDialog.Builder(this);
altDialog.setMessage("No network connection!");
return false;
} else
return true;
}
add this to the manifest file,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
EDIT: To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}

Related

Android - Check internet connection by pinging url address

I need a service in the background that constantly pings google. But I have no idea how to do it. I am new here. My method does not work does not repeat. It only works once and it always returns "false" .
isConnectedToServer function
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}}
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToServer("http://www.google.com",3000)){
Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
}}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I see Not Okay once on the screen. Only once. Even when I have an internet connection. What can I do about it?
try this create a class that extends AsyncTask
public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;
public CheckInternet(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}

Monitor if URL is online constantly in Android

I want to create URL monitor that will monitor in background each x seconds if the URL is online.
ConnectivityManager is not good for me because my app is used in controlled environment and although internet works some ports need to be closed.
So I need to monitor if foo.com/9000 is online all the time and when I request isOnline I want to get the result immediately, so monitoring should be done in background.
How would I accomplish this and is there a library that does this?
In Actionscript I would call UrlMonitor and pass it url
Could you use this to repeat the task:
Repeat a task with a time delay?
This being the task:
HttpGet request = new HttpGet();
URI uri = new URI("your_url");
request.setURI(uri);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().toString().equalsIgnoreCase("HTTP/1.1 200 OK")) {
// it's there
}
private static boolean internetConnectionAvailable;
private static ScheduledExecutorService scheduleTaskExecutor;
public static void stopInternetMonitor() {
if (scheduleTaskExecutor != null && !scheduleTaskExecutor.isShutdown()) {
scheduleTaskExecutor.shutdown();
}
}
public static void startInternetMonitor() {
Runnable runnable = new Runnable() {
#Override
public void run() {
isInternetConnectionAvailableSync();
}
};
if (scheduleTaskExecutor != null) {
if (scheduleTaskExecutor.isShutdown()) {
scheduleTaskExecutor.scheduleWithFixedDelay(runnable, 0, 30, TimeUnit.SECONDS);
}
} else {
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleWithFixedDelay(runnable, 0, 30, TimeUnit.SECONDS);
}
}
public static boolean isInternetConnectionAvailableCached() {
ConnectivityManager cm = (ConnectivityManager) FashionTrenderApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected() && internetConnectionAvailable) {
return true;
}
return false;
}
public static boolean isInternetConnectionAvailableSync() {
ConnectivityManager cm = (ConnectivityManager) FashionTrenderApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
try {
URL url = new URL(EnvironmentConfiguration.getInstance().getServerUrl());
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
internetConnectionAvailable = true;
return true;
} else {
internetConnectionAvailable = false;
return false;
}
} catch (IOException e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
return false;
}

App crashes when wifi is out of range

I have an app that crashes when the wifi on phone goes out of range. It gets strings from an online txt mainly and I do disconnect the HTTPURLConnection after it gets done, so I was not expecting the crash. Below is the relevant code;
To check network availablity(all code that uses an internet connection gets checked by this first):
public boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
My checkForPromptPassword asynctask that runs on onResume:
private class CheckForPromptPasswordAgain extends AsyncTask<Void, Void, Boolean>
{
// ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
// pdLoading.setMessage("\tFetching Database...");
// pdLoading.show();
}
#Override
protected Boolean doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
//view GONE by default of update button
if (isNetworkAvailable()){
if (PromptForPasswordAgain()){
//TODO: //show update button or dialog
return true;
}else{
//TODO: //proceed as normal
return false;
}
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//this method will be running on UI thread
if (result==true){
promptForPassword();
}else{
// showDialog("string", "string",0);
}
// pdLoading.dismiss();
}
}
My checkForUpdate AsyncTask that runs on OnResume():
Private class CheckForUpdate extends AsyncTask<Void, Void, Boolean>
{
// ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
// pdLoading.setMessage("\t string.");
// pdLoading.show();
}
#Override
protected Boolean doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
//view GONE by default of update button
if (fileExistance("data.txt")){
try {
if (isNetworkAvailable()){
if (isDatabaseContentDifferent()){
//TODO: //show update button or dialog
return true;
}else{
//TODO: //proceed as normal
return false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.i("error","file data.txt does not exist in internal");
return false;
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//this method will be running on UI thread
Button updateButton = (Button) findViewById(R.id.UpdateDatabase);
updateButton.setVisibility(View.GONE);
if (result==true){
showDialog("Database Updated On Server", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s). ",0);
updateButton.setVisibility(View.VISIBLE);
}else{
updateButton.setVisibility(View.GONE);
// showDialog("No Update Detected", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s). ",0);
}
// pdLoading.dismiss();
}
}
Example of the HTTPURLClient that I am using, many functions but this is the basic structure:
public boolean isDatabaseContentDifferent() throws IOException{
String page = null;
try{
URL url = new URL(_data);
HttpURLConnection.setFollowRedirects(true);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(false);
con.setReadTimeout(20000);
con.setRequestProperty("Connection", "keep-alive");
//get etag for update check
//String etag= "";
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
((HttpURLConnection) con).setRequestMethod("GET");
//System.out.println(con.getContentLength()) ;
con.setConnectTimeout(5000);
BufferedInputStream in = new BufferedInputStream(con.getInputStream());
//make seperate function for etag it doesn't work with GET
//String etag = con.getHeaderField("etag");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println(responseCode);
}
StringBuffer buffer = new StringBuffer();
int chars_read;
//int total = 0;
while ((chars_read = in.read()) != -1)
{
char g = (char) chars_read;
buffer.append(g);
}
page = buffer.toString();
//create password.txt to internal
//TODO: checkkk
con.disconnect();
}catch(Exception e){
showDialog("Database Fetch Failure","Unable to Fetch Password Database, check your internet" +
" connection and try again later.",0);
Log.i("Page", "Error in isDatabaseContentDifferent()");
return false;
}
if (fileExistance("data.txt")){
if (isTextInFileDifferent(page,"data.txt")){
return true;
}else{
return false;
}
}else{
Log.i("Page","file data.txt does not exist IN isDatabaseContentDifferent()");
return false;
}
}
Any help will be highly appreciated. Thanks.

Check for Active internet connection Android

I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
returnVal = p1.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;
I also tried this code:
if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{ }
else
{ }
but I could not get isReachable to work.
It does works for me:
To verify network availability:
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
To verify internet access:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
I use this:
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
It comes from an other stackoverflow answer but I can't find it.
EDIT:
Finally I found it: https://stackoverflow.com/a/1565243/2198638
Here is some modern code that uses an AsynTask to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user.
class TestInternet extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
doMyStuff();
}
}
}
...
new TestInternet().execute();
To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
if (connectGoogle()) {
return true;
} else { //one more try
return connectGoogle();
}
} else {
log("No network available! (in hasActiveInternetConnection())");
return false;
}
}
public static boolean isNetworkAvailable(Context ct) {
ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
log("IOException in connectGoogle())");
return false;
}
}
Query a website like this:
Make your class implement AsyncTaskCompleteListenere<Boolean> by adding the following method to your class:
#Override
public void onTaskComplete(Boolean result) {
Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
// continue your job
}
Add a simple testConnection method to your class to be called when you want to check for your connectivity:
public void testConnection() {
URLExistAsyncTask task = new URLExistAsyncTask(this);
String URL = "http://www.google.com";
task.execute(new String[]{URL});
}
And finally the URLExistAsyncTask class which perform the connectivity test as an asynchronous (background) task and calls back your onTaskComplete method once done:
public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
AsyncTaskCompleteListenere<Boolean> callback;
public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
this.callback = callback;
}
protected Boolean doInBackground(String... params) {
int code = 0;
try {
URL u = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
return code == 200;
}
protected void onPostExecute(Boolean result){
callback.onTaskComplete(result);
}
}
I did use this method. It worked for me! For people who want to get the real Internet!
public boolean isOnline() {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
httpURLConnection.setRequestProperty("User-Agent", "Test");
httpURLConnection.setRequestProperty("Connection", "close");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.connect();
return (httpURLConnection.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
For doing this method every time! Just use a receiver
and =>
httpURLConnection.getResponseCode() == 200
This means the Internet is connected!
You can do it by create new parallel thread that count time :
final class QueryClass {
private int responseCode = -1;
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if(url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000 );
urlConnection.setConnectTimeout(5000 );
Thread thread = new Thread() {
#Override
public void run() {
super.run();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(responseCode == -1) {
//Perform error message
Intent intent = new Intent(context,ErrorsActivity.class);
intent.putExtra("errorTextMessage",R.string.errorNoInternet);
intent.putExtra("errorImage",R.drawable.no_wifi);
context.startActivity(intent);
}
}
};
thread.start();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}

android progress dialog and threads

I'm trying to show a progress dialog while adding a row to a database table, but the problem is that the progress dialog is only showing for 1 second and the application crashes after that, can anyone help me please ?
public void onClick(View arg0) {
// TODO Auto-generated method stub
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
final EditText wholepost=(EditText)findViewById(R.id.wholepost);
final String post_type=spinner.getSelectedItem().toString();
final String post_type2=post_type.replace(" ", "%20");
final String post1=wholepost.getText().toString();
String post2=post1.replace(" ", "%20");
final String post3=post2.replace("\n","%0D");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
final String now = df.format(new Date());
if(post1.equals(null))
{
Toast.makeText(getBaseContext(), "Please write a post before clicking on the button",Toast.LENGTH_LONG).show();
}
else
{
if(post1.length()<15)
{
Toast.makeText(getBaseContext(), "Post is too small",Toast.LENGTH_LONG).show();
}
else
{
if(post1.length()>500)
{Toast.makeText(getBaseContext(), "Post should be smaller",Toast.LENGTH_LONG).show();}
else
{
pd.show();
Thread th=new Thread(new Runnable() {
public void run() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.1.38/test/Addpost.php?username="+username+"&fname="+firstname+"&lname="+lastname+"&dop="+now+"&content="+post3+"&type="+post_type2+"");
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstN",firstname));
nameValuePairs.add(new BasicNameValuePair("LastN",lastname));
nameValuePairs.add(new BasicNameValuePair("Content",post1));
nameValuePairs.add(new BasicNameValuePair("type",post_type));
nameValuePairs.add(new BasicNameValuePair("Dateofp",now));
nameValuePairs.add(new BasicNameValuePair("username",username));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200)
{
entity=response.getEntity();
if(entity !=null)
{
Toast.makeText(getBaseContext(),"POST SUCCESFULLY ADDED",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getBaseContext(),"ERROR RERTY OR CHECK YOUR CONNECTION",Toast.LENGTH_LONG).show();
}
wholepost.setText("");
}
catch(Exception ex)
{Toast.makeText(getBaseContext(),"CONNECTION ERROR",Toast.LENGTH_LONG).show();}
pd.dismiss();
}
});
th.start();
}}
}
}
else
{
Toast.makeText(getBaseContext(),"Please make sure you're connected to the internet",Toast.LENGTH_LONG).show();
}
}
});
Use Asyntask or otherewise Sleep your thread

Categories