I have created a login page with php and json, but when I go offline and use the program instead showing an error, the program is closed. How can i show this message: "please check your network connection"? Now it says unfortunately start1 has stopped.
Android code:
public class Login extends Activity {
EditText user,pass;
Button btnReg;
private static String url = "http://akosamanus.xzn.ir/Login.php";
private ProgressDialog pd;
JSONParser jparser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.etgetuser);
pass = (EditText)findViewById(R.id.etgetpass);
btnReg = (Button)findViewById(R.id.btnReg);
btnReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new loadperson().execute();
}
});
}
class loadperson extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(Login.this);
pd.setMessage("login");
pd.show();
}
@Override
protected String doInBackground(String... strings) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",username));
params.add(new BasicNameValuePair("password",password));
Log.d("request!", "starting");
JSONObject json = jparser.makeHttpRequest(url, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,com.example.eagle.start1.SelectPage.class);
ii.putExtra("UserName", username);
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String message) {
pd.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_SHORT).show();
}
}
}
First check if the netwrok is connected or not:
public boolean isConnectedToNetwork() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
and then in your onClickListener use it as:
btnReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isConnectedToNetwork())
new loadperson().execute();
else
Toast.makeText(Login.this,"Please check your network connection",Toast.LENGTH_SHORT).show();
}
});
Also add the permission to the AndroidMenifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class ConnectionDetector {
public boolean isConnectingToInternet(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
if (haveConnectedWifi || haveConnectedMobile) {
try {
URL url = new URL("https://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "delete");
urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (Exception e) {
Log.e("internet error", "" + e);
return false;
}
} else {
return false;
}
}
}
and in doInBackground method use isConnectingToInternet(context) if true then continue background task else return some meaningful which define no network.