это мой вход в систему, который я сделал, есть проблема в этом, если интернет-соединение работает нормально, но если нет интернет-соединения, оно показывает сбойное сообщение, пожалуйста, помогите мне решить эту проблему
я использовал Json
public class LoginActivity extends Activity implements OnClickListener{
private EditText etUser,etPassword;
private ImageView bLogin,bCancel,bRegister;
private Spinner spPermission;
private static String[] PERMISSIONS = {"Admin","Donor","Accepter"};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
etUser = (EditText)findViewById(R.id.etUserName);
etPassword = (EditText)findViewById(R.id.etPassword);
etUser.setText("");
etPassword.setText("");
spPermission = (Spinner)findViewById(R.id.spPermission);
ArrayAdapter<String> permAdapter = new ArrayAdapter<String>(LoginActivity.this,android.R.layout.simple_spinner_item,PERMISSIONS);
permAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spPermission.setAdapter(permAdapter);
bLogin = (ImageView)findViewById(R.id.imLogin);
bCancel= (ImageView)findViewById(R.id.imCancel);
bRegister = (ImageView)findViewById(R.id.imRegister);
bLogin.setOnClickListener(this);
bCancel.setOnClickListener(this);
bRegister.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.imLogin:
String uName = etUser.getText().toString();
String password = etPassword.getText().toString();
String type = spPermission.getSelectedItem().toString();
String message = "POST";
LoginTask task = new LoginTask(this);
task.execute(message,uName,password,type);
break;
case R.id.imCancel:
finish();
break;
case R.id.imRegister:
startActivity(new Intent(getApplicationContext(), Registration.class));
break;
default:
break;
}
}
public class LoginTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String login_url = //"http://192.168.1.3/login.php";
"http://10.0.2.2/login.php";
private String s;
private String USER_TYPE;
public LoginTask(Context c)
{
context = c;
}
@Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String uName = params[1];
final String uPass = params[2];
final String uType = params[3];
USER_TYPE = uType;
list.add(new BasicNameValuePair("username", uName));
list.add(new BasicNameValuePair("password",uPass));
list.add(new BasicNameValuePair("type", uType));
json = jsonParser.makeHttpRequest(login_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
@Override
protected void onPostExecute(String result)
{
try {
int success = json.getInt("success");
if(success==1)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
Intent i = new Intent(context.getApplicationContext(),MainView.class);
i.putExtra("type", USER_TYPE);
context.startActivity(i);
}
else
//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
Toast.makeText(context, "Sorry No connection", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
изменить свой doInBackground(
) метод для:
@Override
protected String doInBackground(String... params) {
String message = params[0];
if (message.equals("POST")) {
try {
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String uName = params[1];
final String uPass = params[2];
final String uType = params[3];
USER_TYPE = uType;
list.add(new BasicNameValuePair("username", uName));
list.add(new BasicNameValuePair("password", uPass));
list.add(new BasicNameValuePair("type", uType));
json = jsonParser.makeHttpRequest(login_url, params[0], list);
}
s = json.getString("message");
}catch(Exception ex){
ex.printStackTrace();
}catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
}
перед вызовом asyntask проверьте подключение к интернету следующим образом
поместите это в некоторый класс констант
public static boolean isConnectingToInternet(){
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;
}
и во время вызова asyntask проверьте подключение с помощью следующих
if(Constants.isConnectingToInternet()) {LoginTask task = new LoginTask(this);
task.execute(message,uName,password,type);}
Это определенно будет работать.
ваш класс будет как
public class LoginActivity extends Activity implements OnClickListener{
private EditText etUser,etPassword;
private ImageView bLogin,bCancel,bRegister;
private Spinner spPermission;
private static String[] PERMISSIONS = {"Admin","Donor","Accepter"};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
Constants.context=this;
etUser = (EditText)findViewById(R.id.etUserName);
etPassword = (EditText)findViewById(R.id.etPassword);
etUser.setText("");
etPassword.setText("");
spPermission = (Spinner)findViewById(R.id.spPermission);
ArrayAdapter<String> permAdapter = new ArrayAdapter<String>(LoginActivity.this,android.R.layout.simple_spinner_item,PERMISSIONS);
permAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spPermission.setAdapter(permAdapter);
bLogin = (ImageView)findViewById(R.id.imLogin);
bCancel= (ImageView)findViewById(R.id.imCancel);
bRegister = (ImageView)findViewById(R.id.imRegister);
bLogin.setOnClickListener(this);
bCancel.setOnClickListener(this);
bRegister.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.imLogin:
String uName = etUser.getText().toString();
String password = etPassword.getText().toString();
String type = spPermission.getSelectedItem().toString();
String message = "POST";
if(Constants.isConnectingToInternet()) {LoginTask task = new LoginTask(this);
task.execute(message,uName,password,type);}break;
case R.id.imCancel:
finish();
break;
case R.id.imRegister:
startActivity(new Intent(getApplicationContext(), Registration.class));
break;
default:
break;
}
}
public class LoginTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String login_url = //"http://192.168.1.3/login.php";
"http://10.0.2.2/login.php";
private String s;
private String USER_TYPE;
public LoginTask(Context c)
{
context = c;
}
@Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String uName = params[1];
final String uPass = params[2];
final String uType = params[3];
USER_TYPE = uType;
list.add(new BasicNameValuePair("username", uName));
list.add(new BasicNameValuePair("password",uPass));
list.add(new BasicNameValuePair("type", uType));
json = jsonParser.makeHttpRequest(login_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
@Override
protected void onPostExecute(String result)
{
try {
int success = json.getInt("success");
if(success==1)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
Intent i = new Intent(context.getApplicationContext(),MainView.class);
i.putExtra("type", USER_TYPE);
context.startActivity(i);
}
else
//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
Toast.makeText(context, "Sorry No connection", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
и ваш класс констант будет
public class Constants {
public static final Context context=null;
public static boolean isConnectingToInternet(){
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;
}
}