how to check internet connection in asynctask in android - android

#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.videoView1);
scanCode = getIntent().getExtras().getString("ScanCode");
new GetVideoUrlAsyn().execute();
mVideoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(),
PostVideoMenuActivity.class));
}
});
}
private class GetVideoUrlAsyn extends AsyncTask<Void, Void,Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String URL = "http://www.storybehindthestore.com/sbtsws/service/saveinfo.asmx/StoryScanHistorySave";
WebServiceCall webservice = new WebServiceCall();
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("iSiteID","1"));
nameValuePairs.add(new BasicNameValuePair("sVideoURL",scanCode));
Log.e("scancode",""+ scanCode);
nameValuePairs.add(new BasicNameValuePair("sDeviceID",SplashActivity.deviceId));
Log.e("sDeviceID",""+ SplashActivity.deviceId);
nameValuePairs.add(new BasicNameValuePair("sDeviceModel",SplashActivity.deviceModelName));
Log.e("sDeviceModel",""+ SplashActivity.deviceModelName);
responce = webservice.callhttppost_numvaluepair(URL, nameValuePairs);
// Log.e("Stiryscanstorysave responce", responce);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//progressDialog.dismiss();
if (responce.contains("InCorrect QR Code !")) {
AlertDialog adddrug1 = new AlertDialog.Builder(
VideoActivity.this)
.setTitle("Message")
.setMessage("InCorrect QR Code !")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
startActivity(new Intent(getBaseContext(),
HomeActivity.class));
}
}).create();
adddrug1.show();
}else {
StoryScanSaveListGet();
mVideoView.setVideoURI(Uri.parse(scanCode));
mVideoView.setMediaController(new MediaController(VideoActivity.this));
mVideoView.requestFocus();
mVideoView.start();
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog = new ProgressDialog(VideoActivity.this);
progressDialog.setCancelable(false);
progressDialog.show(); */
}
public void StoryScanSaveListGet() {
// TODO Auto-generated method stub
id.clear();
site_id.clear();
store_name.clear();
store_url.clear();
store_phone.clear();
video_count.clear();
try {
JSONObject jmain = new JSONObject(responce);
JSONArray jarray = jmain.getJSONArray("tblCustomer");
JSONObject j_one = (JSONObject) jarray.get(0);
Log.v("Responce", responce);
for (int i = 0; i < jarray.length(); i++) {
j_one = (JSONObject) jarray.get(i);
id.add(j_one.get("id").toString());
site_id.add(j_one.get("site_id").toString());
store_name.add(j_one.get("store_name").toString());
store_url.add(j_one.get("store_url").toString());
store_phone.add(j_one.get("store_phone").toString());
video_count.add(j_one.get("video_count").toString());
}
storeurl =j_one.get("store_url").toString();
storephone = j_one.get("store_phone").toString();
videocount = j_one.get("video_count").toString();
storename = j_one.get("store_name").toString();
Log.i("id", ""+ id);
Log.i("site_id", ""+ site_id);
Log.i("store_name", ""+ store_name);
Log.i("store_url", ""+ store_url);
Log.i("store_phone", ""+ store_phone);
Log.i("video_count", ""+ video_count);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
responce = null;
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
Log.d("tag", "onPause called");
super.onPause();
stopPosition = mVideoView.getCurrentPosition(); // stopPosition is an
// int
mVideoView.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("TAG", "onResume called");
mVideoView.seekTo(stopPosition);
mVideoView.start(); //
}
hii i want to open alert if internet is not available and also check if response getting time out..how is it posible??? help me..here is my code of asynctask which is new GetVideoUrlAsyn().execute(); method..

Check network connectivity before executing AsyncTask,
if(isNetworkAvailable(this))
{
new GetVideoUrlAsyn().execute();
}
and this is the method definition,
public boolean isNetworkAvailable(Context ctx)
{
ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()&& cm.getActiveNetworkInfo().isAvailable()&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
do something like this inside your method callhttppost_numvaluepair(URL, nameValuePairs) of WebServiceCall class,
HttpParams basicparams = new BasicHttpParams();
URI uri = new URI(url);
HttpPost method = new HttpPost(uri);
int timeoutConnection = 60000;//set your timeout period
HttpConnectionParams.setConnectionTimeout(basicparams,
timeoutConnection);
DefaultHttpClient client = new DefaultHttpClient(basicparams);
//and then rest of your code
Note:
Don't forget to put the permission in manifest file,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

You should use a broadcast receiver as mentioned in other SO answers, but since you have asked how to do this otherwise, here you go:
* Checks for an existing network connectivity
*
* #param context
* The {#link Context} which is needed to tap
* {#link Context#CONNECTIVITY_SERVICE}
* #return True if network connection is available
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
Will need additional permission to be specified in the manifest file

check internet before execute asyncTask
if(checkNetwork)
{
new GetVideoUrlAsyn().execute();
}
else
{
// do stuff
}

if(CheckNetwork){
new GetVideoUrlAsyn().execute();
}else{
// Check internet connection
}
and
private boolean CheckNetwork() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}

Related

Show ProgressDialog fails

I know that there is a lot of questions about this, but I'm desperated...
I'm trying to show a Dialog while doing an AsyncTask, that must be easy but I'm no able to do it...
I had tried with .execute() and .get() and I had put a for to make the task take a long time, but nothing..
Here is my class:
public class OrdenNuevaActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Log.v("FLUJO", this.getClass().toString());
super.onCreate(bundle);
setContentView(R.layout.activity_orden_nueva);
aceptarOrdenNuevaButton = (Button) findViewById(R.id.aceptarOrdenNuevaButton);
aceptarOrdenNuevaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase tareaCambiarEstadoOrdenEnBDServer = new TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(idOrden, Estados.ACEPTADO,OrdenNuevaActivity.this);
try {
tareaCambiarEstadoOrdenEnBDServer.execute();
} catch (Exception e) {
e.printStackTrace();
}
Toast toast1 = Toast.makeText(getApplicationContext(), "Orden Aceptada", Toast.LENGTH_SHORT);
toast1.show();
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
UtilsVictor.addPuebloAlAceptarOrden(context,terminoOrdenAceptadaDetalleTV.getText().toString());
finish();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdenNuevaActivity.this).create();
alertDialog.setTitle("ERROR!");
alertDialog.setMessage("NO hay cobertura, vuelva a intentarlo mas tarde");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setIcon(R.drawable.common_signin_btn_icon_normal_light);
alertDialog.show();
}
}
});
}
public class TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase extends AsyncTask<String,Integer,Boolean>{
private static final String TAG = "AppMovil";
private Integer mOrdenId;
private String mEstadoString;
boolean resul = true;
boolean tareaRealizada = false;
boolean catchPasado = false;
private Context mContext;
private ProgressDialog mPD;
public TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(Integer idO ,String estadoO, Context cntx) {
mContext = cntx;
mOrdenId = idO;
mEstadoString = estadoO;
mPD = new ProgressDialog(mContext);
}
public boolean getResultado(){
return resul;
}
public boolean getTareaRealizada(){
return tareaRealizada;
}
public boolean getCatchPasado(){
return catchPasado;
}
#Override
protected void onPreExecute() {
mPD.setTitle("Please Wait..");
mPD.setMessage("Loading...");
mPD.setCancelable(false);
mPD.show();
}
#Override
protected Boolean doInBackground(String... params) {
for(int i=0; i<999999;i++){
Log.v("A", "A");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", mOrdenId);
jsonObject.put("estado", mEstadoString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URIS.URI_TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString);
post.setHeader("content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode >200 & responseCode < 400) {
Log.v(TAG, "Orden Enviada OK a nuestro Server");
tareaRealizada = true;
resul = true;
} else {
Log.v(TAG, "FALLO al Enviar Orden a nuestro Server");
resul = false;
tareaRealizada = true;
}
} catch (Exception e) {
catchPasado = true;
resul = false;
e.printStackTrace();
}
return resul;
}
#Override
protected void onCancelled() {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onPostExecute(Boolean result) {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
Where is the mistake?

How can i send data to server from android service? [duplicate]

I know there are many questions that have been asked regarding this and i have been going through all that from couple of days but could'nt find a reasonable answer. i am newbie to android and php so i have no idea how things get done.
so basically first i want to know how to run gps as a service in background like when the application is installed it starts and periodically send the coordinates to web server?
Just create a service that runs in the background all the time.
For Example:-
AndroidLocationServices
public class AndroidLocationServices extends Service {
WakeLock wakeLock;
private LocationManager locationManager;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
if (isConnectingToInternet(getApplicationContext())) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
jsonObject.put("latitude", location.getLatitude());
jsonObject.put("longitude", location.getLongitude());
jsonArray.put(jsonObject);
Log.e("request", jsonArray.toString());
new LocationWebService().execute(new String[] {
Constants.TRACK_URL, jsonArray.toString() });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wakeLock.release();
}
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
LocationWebService
public class LocationWebService extends AsyncTask<String, String, Boolean> {
public LocationWebService() {
// TODO Auto-generated constructor stub
}
#Override
protected Boolean doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", arg0[1]));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(arg0[0]);
HttpParams httpParameters = new BasicHttpParams();
httpclient = new DefaultHttpClient(httpParameters);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Log.e("Google", "Server Responded OK");
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
You can find a sample project with Android App and corresponding WebFiles within this github project androidbackgroundgps

Connection Loss Handling in AsyncTask in Android

In My application i have read all the record from the DataBase SqlServer by using REST API.But there is some problem when connection loss at intermediate execution of protected DetailsTimeTable doInBackground(String... params). Then my app closed with error Unfortunately app has stopped
Here is my Code:
public class Monday_Time extends ListActivity {
ArrayList<String> itemsList = new ArrayList<String>();
private ProgressDialog progressDialog;
private BroadcastReceiver mconn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.time_table_list);
// Bundle bundle = getIntent().getExtras();
Toast.makeText(this, MainActivity.branch_static, Toast.LENGTH_LONG).show();
// registerReceiver(new NetworkBroadCast(), new IntentFilter(ConnectivityManager.EXTRA_IS_FAILOVER));
mconn = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isfailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
Log.d("Connectivity", Boolean.toString(noConnectivity));
Log.d("Reson ", reason);
Log.d("FailOver", Boolean.toString(isfailOver));
}
};
registerReceiver(mconn, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
new AsyncDetailsTimeTable().execute(MainActivity.branch_static.trim(), MainActivity.sem_static.trim(), MainActivity.sec_static.trim(), "Monday");
}
public class AsyncDetailsTimeTable extends AsyncTask<String, Void, DetailsTimeTable> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(Monday_Time.this);
progressDialog.setMessage("Loding Time Table....");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(DetailsTimeTable result) {
// TODO Auto-generated method stub
// Log.d("POST DATA", result.getFirst());
progressDialog.dismiss();
if (SSTCTimeTableTabActivity.ram == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(Monday_Time.this);
builder.setMessage("Time Table is not availble....")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do things
startActivity(new Intent(Monday_Time.this, com.src.sstctimetable.MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
itemsList.add("1:: " + result.getFirst());
itemsList.add("2:: " + result.getSecond());
itemsList.add("3:: " + result.getThird());
itemsList.add("4:: " + result.getFourth());
itemsList.add("5:: " + result.getFifth());
itemsList.add("6:: " + result.getSixth());
itemsList.add("7:: " + result.getSeventh());
setListAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.rowlayout, R.id.label, itemsList));
}
super.onPostExecute(result);
}
#Override
protected DetailsTimeTable doInBackground(String... params) {
DetailsTimeTable userDetail = null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetTimeTableDetails(params[0], params[1], params[2], params[3]);
JSONParser parser = new JSONParser();
userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail;
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
// Log.d("AsyncUserDetails", e.getMessage());
}
Try to comment Log print. I think e.getmessage() throwing NullPointerException.

Application close when rotate main (Activity ) screen in android

I am making two layout one is for Landscape and another is for portrait.
And make layout-land folder for Landscape and put all landscape layout, All Landscape Layout is working fine but when i rotate on Main Activity then It,s close.
removed layout-land folder and tried then again close the App
Main Activity
<activity
android:name=".UnsignPropertyAlert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
UnsignPropertyAlert class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unsignalert);
Commons.setContext(context);
listView =(ListView) findViewById(R.id.list);
// listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
btnregister= (TextView) findViewById(R.id.login);
btnNext= (Button) findViewById(R.id.btnnext);
btnPrev= (Button) findViewById(R.id.btnprev);
AdView adView = (AdView)this.findViewById(R.id.adView);
//adView.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
Bundle bundle = new Bundle();
bundle.putString("color_bg","#fdfbfc");
bundle.putString("color_text", "#81BE32");
AdMobExtras extras = new AdMobExtras(bundle);
adRequest = new AdRequest.Builder()
.addNetworkExtras(extras)
.build();
// btnNext.setVisibility(View.INVISIBLE);
// btnPrev.setVisibility(View.INVISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
nextProp();
}
});
btnPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
prevProp();
}
});
login = new File("/data/data/com.dwellesque/shared_prefs/Login.xml");
if(Commons.HaveNetworkConnection(context))
{
if(login.exists())
{
btnregister.setText("LOGIN");
preferences=getSharedPreferences("Login", MODE_PRIVATE);
String zip= preferences.getString("ZIP", "");
url="http://www.......";
backurl="http://www.....";
}
else
{
url="http://www......";
backurl="http://www.......";
}
pd=new ProgressDialog(UnsignPropertyAlert.this,ProgressDialog.THEME_HOLO_LIGHT);
pd.setMessage("Loading....");
pd.setTitle(null);
pd.show();
url=url.replace(" ", "%20");
Log.d("First", url);
JsonRequestAsycn task=new JsonRequestAsycn();
task.execute(url);
task.delegate=UnsignPropertyAlert.this;
}
else
{
Toast.makeText(context, "Please check your internet connection! ", Toast.LENGTH_LONG).show();
}
btnSearch= (TextView) findViewById(R.id.search);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(UnsignPropertyAlert.this,Main_Serach.class));
}
});
btnregister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(btnregister.getText().toString().equals("LOGIN"))
{
startActivity(new Intent(UnsignPropertyAlert.this,Login.class));
}
else
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www......."));
startActivity(browserIntent);
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String url = arlisturl.get(position);
Log.d("URL", url);
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
listView.setOnTouchListener(new OnSwipeTouchListener(context) {
#Override
public void onSwipeLeft() {
// Whatever
nextProp();
// Toast.makeText(context, "left", Toast.LENGTH_LONG).show();
}
public void onSwipeRight() {
// Whatever
prevProp();
// Toast.makeText(context, "Right", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void processFinish(String output) {
pd.dismiss();
// TODO Auto-generated method stub
if(output.trim().contains("Result not found !") || output.length()==114 || output.length()<1)
{
Toast.makeText(context, "Property Not Found", Toast.LENGTH_LONG).show();
}
else if(output.trim().contains("TimeOut"))
{
Toast.makeText(context, "Connection Timeout!", Toast.LENGTH_LONG).show();
}
else
{
showdata(output,listView,true);
}
}
// Set Data in List View
void showdata(String data,ListView lv,Boolean first)
{
doc = XMLfunctions.XMLfromString(data);
NodeList nodes = doc.getElementsByTagName("PROPERTY");
for (int i = 0; i<nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
// Street Name
if (!("null").equals(XMLfunctions.getValue(e, "street"))) {
arliststitname.add(XMLfunctions.getValue(e, "street"));
} else {
arliststitname.add(" ");
}
// Location
if (!("null").equals(XMLfunctions.getValue(e, "city"))) {
if(!("null").equals(XMLfunctions.getValue(e, "state")))
{
arlistlocation.add(XMLfunctions.getValue(e, "city")+" ,"+XMLfunctions.getValue(e, "state"));
}
arlistlocation.add(XMLfunctions.getValue(e, "city"));
} else {
arlistlocation.add(" ");
}
// Square Footage
if (!("null").equals(XMLfunctions.getValue(e, "SquareFootage"))) {
arlistsqare.add(XMLfunctions.getValue(e, "SquareFootage"));
} else {
arlistsqare.add(" ");
}
// price
if (!("null").equals(XMLfunctions.getValue(e, "price"))) {
arlistprice.add(XMLfunctions.getValue(e, "price"));
} else {
arlistprice.add(" ");
}
// Images
if (!("null").equals(XMLfunctions.getValue(e, "picture"))) {
String[] imageUrls=XMLfunctions.getValue(e, "picture").split("\\|\\|");
arlistimg.add(imageUrls[0]);
} else {
arlistimg.add("");
}
// posted on
if (!("null").equals(XMLfunctions.getValue(e, "EnteredDate"))) {
arlistposted.add(XMLfunctions.getValue(e, "EnteredDate"));
} else {
arlistposted.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "description"))) {
arlistDesc.add(XMLfunctions.getValue(e, "description"));
} else {
arlistDesc.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "propertystatus"))) {
arlistproperty.add(XMLfunctions.getValue(e, "propertystatus"));
} else {
arlistproperty.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "EnteredDate"))) {
arlistyear.add(XMLfunctions.getValue(e, "EnteredDate"));
} else {
arlistyear.add("");
}
//URL
if (!("null").equals(XMLfunctions.getValue(e, "propertyurl"))) {
arlisturl.add(XMLfunctions.getValue(e, "propertyurl"));
} else {
arlisturl.add("");
}
// ID
if (!("null").equals(XMLfunctions.getValue(e, "id"))) {
arlistID.add(XMLfunctions.getValue(e, "id"));
} else {
arlistID.add("");
}
}
if(first)
{
lv.setAdapter(null);
String[] Street={ arliststitname.get(0) };
adapter= new
AlertListAdapter(context,arlistimg.get(0), Street, arlistlocation.get(0),
arlistsqare.get(0), arlistprice.get(0),arlistposted.get(0),arlisturl.get(0),arlistID.get(0));
lv.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(login.exists())
{
btnregister.setText("LOGIN");
}
}
#Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
else
return true;
}
}
return false;
}
#Override
public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
void nextProp()
{
if(Commons.HaveNetworkConnection(context))
{
if(proppos<arliststitname.size()-2)
{
btnPrev.setEnabled(true);
proppos++;
listView.setAdapter(null);
String[] Street={ arliststitname.get(proppos) };
adapter= new
AlertListAdapter(context,arlistimg.get(proppos), Street, arlistlocation.get(proppos),
arlistsqare.get(proppos), arlistprice.get(proppos),arlistposted.get(proppos),arlisturl.get(proppos),arlistID.get(proppos));
listView.setAdapter(adapter);
}
else
{
start=start+10;
String newurl=backurl+"&start="+start;
Log.d("URL", newurl);
Backgrounddata getData= new Backgrounddata();
getData.execute(newurl);
}
}
}
void prevProp()
{
if(Commons.HaveNetworkConnection(context))
{
if(proppos<=0)
{
btnPrev.setEnabled(false);
}
else
{
proppos--;
listView.setAdapter(null);
String[] Street={ arliststitname.get(proppos) };
adapter= new
AlertListAdapter(context,arlistimg.get(proppos), Street, arlistlocation.get(proppos),
arlistsqare.get(proppos), arlistprice.get(proppos),arlistposted.get(proppos),arlisturl.get(proppos),arlistID.get(proppos));
listView.setAdapter(adapter);
}
}
}
// background hit data
private class Backgrounddata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
for (String url : urls) {
// Create the client
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// Execute HTTP Post Request and get response
// Set connection timeout
int timeoutConnection = 15000 ;
HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), timeoutConnection);
// set socket timeout
int timeoutSocket = 15000 ;
HttpConnectionParams.setSoTimeout(httpGet.getParams(), timeoutSocket);
HttpResponse responsePOST = client.execute(httpGet);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
}
} catch (Exception e) {
return "TimeOut";
// e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
pd.dismiss();
try{
showdata(result,listView,false);
}
catch(Exception e)
{
Log.d("error hai",""+e);
}
}
#Override
protected void onPreExecute()
{
pd=new ProgressDialog(UnsignPropertyAlert.this,ProgressDialog.THEME_HOLO_LIGHT);
pd.setMessage("Loading....");
pd.setTitle(null);
pd.show();
}
}
Please Help Me How can fix this issue
Thanks In Advance

How to perform AsyncTask for checking internet connection

I have the following code, and what I'm trying to do is to programmatically check if there is an internet connection or not.
Since I'm getting a NetworkOnMainThreadException, and have been advised to use AsyncTask.
I want to perform network operation on hasActiveInternetConnection(Context context)and return true if connected to a network, else false .
How do I do this using AsyncTask?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
}
// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
use this class for checking internet connectivity...
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
then.....
use the this ASynTask for httppost.
public class NetworkUtil extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
There is no way to get an Internet connexion state, you will always have the network connection state.
But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!
here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
#Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Your AsyncTask should look like this:
private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
Context context;
public NetworkUtilTask(Context context){
this.context = context;
}
protected Boolean doInBackground(Void... params) {
return hasActiveInternetConnection(this.context);
}
protected void onPostExecute(Boolean hasActiveConnection) {
Log.d(LOG_TAG,"Success=" + hasActiveConnection);
}
}
You would then execute it like the following:
NetworkUtilTask netTask = new NetworkUtilTask(context);
netTask.execute();

Categories

Resources