I am working with android studio and whenever I try to connect to internet it show Dialog that "Unfortunately 'app name' stopped" and then if crashes.
I have updated the manifest file for permission as well. please provide any assistance, It might helpful.
Here is the code:
public class Login extends Activity {
TextView msg;
String user,pass;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText password;
TextView regLabel;
Button loginbt;
final EditText username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
regLabel = (TextView) findViewById(R.id.register_label);
msg = (TextView) findViewById(R.id.alert);
regLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register_form = new Intent(Login.this,Register.class);
startActivity(register_form);
}
});
loginbt = (Button) findViewById(R.id.login);
loginbt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
user = username.getText().toString();
pass = password.getText().toString();
if(user.length()>0 && pass.length()>0) {
try {
new LoginProcess().execute("http://url.com");
} catch (Exception le) {
msg.setText("Error:" + le);
}
}else{
msg.setText("Please Enter Username and Password!");
}
}
});
}
public class LoginProcess extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
protected void onPreExecute(){
Dialog.setMessage("Checking Authentication..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
if (Error != null) {
msg.setText("Error in Login: " + Error);
} else {
try {
JSONObject jsonObj = new JSONObject(Content);
String orgPass = jsonObj.getString("password");
if (orgPass.equals(pass)) {
Intent rp = new Intent(Login.this, Menu.class);
startActivity(rp);
finish();
} else {
msg.setText("Wrong Password");
}
} catch (Exception je) {
msg.setText("Error:" + je);
}
}
}
}
}
Related
I'm having a very strange problem. I have an app in playstore with name "Central Department of Physics " Few Days back I was able to connect to my php Databaste from my colors X114 which is Android 4.4 and also checked with Samsung Galaxy with android version samme and it was connected sucessfully but now I haven't changed anything but when I connect to php server I get "Server connection Failed" since few days.
But when I try to connect from Higher android version device, It connects sucessfully...I tried with 3-4 device and result was positive.
So can anyone please help me what should I do to fix this problem??
My activity File is
public class MainActivity extends AppCompatActivity {
private Toolbar mainToolbar;
private Menu mymenu;
protected EditText username;
private Button registerbutton;
private EditText password;
protected String enteredUsername;
private ProgressBar loginProgress;
private final String serverUrl = "https://forappinthenameofking.000webhostapp.com/index.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainv);
loginProgress = findViewById(R.id.login_progressv);
registerbutton = findViewById(R.id.registerbuttonm);
mainToolbar = (Toolbar) findViewById(R.id.mainv);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle("Central Department of Physics");
mainToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newPostIntent = new Intent(MainActivity.this, com.nepalpolice.cdp.MainActivity.class);
startActivity(newPostIntent);
}
});
username = (EditText)findViewById(R.id.username_field);
password = (EditText)findViewById(R.id.password_field);
Button loginButton = (Button)findViewById(R.id.login);
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, form.class);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginProgress.setVisibility(View.VISIBLE);
enteredUsername = username.getText().toString();
String enteredPassword = password.getText().toString();
if(enteredUsername.equals("") || enteredPassword.equals("")){
Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
return;
}
if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){
Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mymenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView) inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setDuration(500);
iv.startAnimation(rotation);
item.setActionView(iv);
return true;
}
return super.onOptionsItemSelected(item);
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
loginProgress.setVisibility(View.VISIBLE);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
loginProgress.setVisibility(View.INVISIBLE);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
I made the login and signup page in android. I want correct data enter in the login form and than its login but when i use incorrect username and password its still login and shows the error like this :- org.json.JSONException: No value for res_response because when i signup the page my data going on the server through url in the format of JSON object.
Registration.java
public class Registration extends Activity {
EditText username, email, password, mobile;
String url = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
Button btnRegister;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
username = (EditText) findViewById(R.id.editname);
email = (EditText) findViewById(R.id.editemail);
password = (EditText) findViewById(R.id.editpassword);
mobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton) findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String emaill = email.getText().toString().trim();
final String passwordd = password.getText().toString().trim();
final String mobilee = mobile.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(emaill)) {
email.setError("Please enter your email");
email.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
email.setError("Enter a valid email");
email.requestFocus();
return;
}
if (TextUtils.isEmpty(passwordd)) {
password.setError("Enter a password");
password.requestFocus();
return;
}
if (TextUtils.isEmpty(mobilee)) {
mobile.setError("Enter a mobile number");
mobile.requestFocus();
return;
}
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "signup");
parameters.put("username", username.getText().toString());
parameters.put("email", email.getText().toString());
parameters.put("mobileno", mobile.getText().toString());
parameters.put("password", password.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" + response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
Mainactivity.java (Its login)
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
String url = "http://codexpertise.com/codexpertise.com/apitest/login.php";
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, passwordd;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
passwordd = (EditText)findViewById(R.id.password);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String pass = passwordd.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(pass)) {
passwordd.setError("Please enter your Password");
passwordd.requestFocus();
return;
}
else {
Intent i = new Intent(MainActivity.this,Userlist.class);
startActivity(i);
}
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "userlogin");
parameters.put("username", username.getText().toString());
parameters.put("password", passwordd.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" +response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg=="+resp_msg);
Toast.makeText(MainActivity.this, "response msg=="+resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
Change this:
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
To:
if (resp_code.equals("200")) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Registration.this,"Donot Match",Toast.LENGTH_SHORT).show();
}
call compare_version() method in else condition
First you have to understand the different between the login success response and the login failed(on a wrong username password combination) response.
You are reading "res_response" value from your JSON response although it is not in your login failed response.
Also you did a mistake in your code by hard-coding resp_code = "200";
I'm facing an issue with AsyncTask doInBackground method, I don't know how to stop this method from running.
I'm working on an application that has a login screen which retrieves information about the logged user. The problem is when I enter a wrong password or username and then when I re-enter the correct data, my application crashes and I get
"java.lang.IllegalStateException: Cannot execute task: the task has
already been executed"
How can I stop this thread from running? Here is the code:
LoginActivity.java
public class LoginActivity extends Activity implements LoginParser.GetLoginListener{
public LoginParser parser1;
public EditText ETUsername;
public EditText ETPassword;
//private LoginParser lb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parser1 = new LoginParser();
ETUsername = (EditText)findViewById(R.id.ET1);
ETPassword = (EditText)findViewById(R.id.ET2);
final Button button = (Button) findViewById(R.id.loginBut);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String UserName = ETUsername.getText().toString();
String Password = ETPassword.getText().toString();
Log.e("LoginAct .. userName: ", UserName);
Log.e("LoginAct .. Password: ", Password);
if (UserName.isEmpty() || Password.isEmpty()) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Please Enter your Username and Password")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
else{
parser1.getLoginInfo(UserName, Password);
parser1.setListener(LoginActivity.this);
}
} // end of button on click
} );
}
#Override
public void didReceivedUserInfo(String displayName) {
if(displayName != null) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent (LoginActivity.this, MainActivity.class);
startActivity(in);
}
}).show();
}
else {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Error in login ID or Password, Please try again later")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
LoginParser.java
public class LoginParser extends AsyncTask <Void,Void,String> {
private String requestURL;
public String UserName ;
public String Password ;
public interface GetLoginListener
{
public void didReceivedUserInfo (String displayName);
}
private GetLoginListener listener;
public GetLoginListener getListener() {
return listener;
}
public void setListener(GetLoginListener listener) {
this.listener = listener;
}
public void getLoginInfo(String userName , String password)
{
requestURL = "some link";
this.UserName = userName ;
this.Password = password ;
execute(); // it will call doInBackground in secondary thread
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(requestURL);
HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();
String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
Log.e("LoginParser","JSONString: " + jsonString);
urlConnection1.setDoOutput(true);
urlConnection1.setRequestMethod("POST");
urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection1.setRequestProperty("charset","utf-8");
PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
// out.print(this.requestMessage);
out.print(jsonString);
out.close();
int statusCode = urlConnection1.getResponseCode();
Log.d("statusCode", String.valueOf(statusCode));
StringBuilder response = new StringBuilder();
byte[] data = null;
if (statusCode == HttpURLConnection.HTTP_OK)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
}
else {
data = null;// failed to fetch data
}
String responseString = new String(data);
Log.e("doInBackground", "responseString" + responseString);
JSONObject jsonObject2 = new JSONObject(responseString);
String Status = jsonObject2.getString("Status");
Log.e("Status", Status);
if (Status.equals("s")) {
Log.i("Status:", "Successful");
String displayName = jsonObject2.getString("DisplayName");
return displayName;
}
else {
return null;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String displayName) {
super.onPostExecute(displayName);
Log.e("onPost: ","onPost");
listener.didReceivedUserInfo(displayName);
}
}
Thank you for your help.
The "can't re-execute task" error can be solved by creating a new instance of the AsyncTask. You can't call execute twice on the same instance, but you can make as many instances as you want.
Stopping the execution won't help that error. The problem isn't that its currently running, the problem is that you need to create a new instance and run that instead.
You can cancel Async task using continuous check of isCancel in your doInBackground method.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Hope this will help you.
I am new to android JSON programming. I want to use set and get function in this program ,but when i used get() for full_name,getting null.
public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
private void getLogin(JSONObject response) {
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
LoginBean loginBean = new LoginBean();
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
LoginBean loginBean = new LoginBean();
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
}
JSON Input:
"{
""user_name"":""ashish#soms.in"",
""user_password"":""123456"",
""device_token"":""1111"",
""mac_address"":""1111"",
""gps_latitude"":""1111"",
""gps_longitude"":""1111""
}"
Here is JSON Response:
{
""data"": {
""user_id"": ""90"",
""full_name"": ""ashish"",
""display_name"": ""ashish"",
""user_image"": ""images/noimage.png"",
""gender"": ""0"",
""authorization_key"": ""4eef1d65f7b470dbca881fe6452ec11457f54489""
}
}
pls comment line LoginBean loginBean = new LoginBean(); then try .
try this code
private void getLogin(JSONObject response) {
LoginBean loginBean=null;
if (response != null){
try {
loginBean = new LoginBean();
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
The reason is that ones i fill in my user name, and password and click login button it is loads again at page requires tu fill user name, and password here is my source code
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
// i am passing this intent
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
});
}
and in mine ViewActivity also
public class ViewActivity extends Activity {
private WebView webView;
public String pass_word;
public String user_name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
//here i get them
getIntent().getStringExtra("username");
getIntent().getStringExtra("password");
webView.loadUrl("http://intranet.mdis.uz/");
}
but this doest works(( i spended 8 hours on research but nothing helped me
I think this line is wrong:
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
you should not use ApplicationContext when you trying to start new activity. Try this:
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
EDIT:
Try this, it should send data via POST:
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
String username = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
String data = "username=" + username + "&password=" + password;
webView.postUrl("http://intranet.mdis.uz/", EncodingUtils.getBytes(data, "base64"));
Let me try it.
Do the modification like this once and see plz...
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
ConnectionClass cc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
cc=new ConnectionClass(this);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
user_name=Uri.encode(user_name); // you can encode your parameters so that it does not throw exception for e.g it will replace a space as %20 otherwise if user enters special character error will come.. :)
pass_word=Uri.encode(pass_word); // same as above
String url="http://myserver.com/login.php?username="+user_name"&password="+user_name; // this is your server page url and passing username and password in plain url u can test it in browser to verify its working :)
new AsyncTask<String,Void,String>() // new android versions does not allow network operations on main thread but need to do asynchronously...
{
#Override
protected String doInBackground(String... params) {
return cc.getServerResponse(params[0]);
}
#Override
protected void onPostExecute(String result) { // this method runs on UI thread and is called when background process is done to make it more fancy u can use onPreExecute() to show a loader and dismiss the dialog here :)
super.onPostExecute(result);
if(result!=null)
{
if(result.equals("1") // assuming u r returning "1" if successful.
{
Toast.makeText(context, "Successful", 2000).show();
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
}
else
Toast.makeText(context, "Network problem...", 2000).show();
}
}.execute(url);
}
}
});
}
Here is the ConnectionClass
public class ConnectionClass {
Context context;
public ConnectionClass(Context ctx) {
this.context=ctx;
}
public String getServerResponse(String urlLink)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpPost http_get = new HttpPost(url);
HttpResponse responses;
responses = client.execute(http_get);
if (responses != null)
{
InputStream in = responses.getEntity().getContent();
String a = convertStreamToString(in);
// Log.i("RETURN",a+"");
return a;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io2", Toast.LENGTH_LONG).show();
}
finally
{
try
{
is.close();
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io3", Toast.LENGTH_LONG).show();
}
}
return sb.toString();
}
}
Hope it helps u :)
Thx