How to set data from JSON? - java

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();
}

Related

Error occurs in Login and signup using API

I updated the code again and after calling the API its show the null. I don't understand it why i getting this problem in my code. I parse it properly but still i getting problem in signup and login in API. How its work to show the data in the sql database?
MainActivity.java (This is a Registration form )
public class MainActivity extends AppCompatActivity {
Button register, log_in;
EditText Username, Email, Password, Mobile ;
String Username_Holder, Email_Holder, PasswordHolder, MobileHolder;
String finalResult ;
String HttpURL = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Assign Id'S
Username = (EditText)findViewById(R.id.username);
Email = (EditText)findViewById(R.id.Email);
Password = (EditText)findViewById(R.id.password);
Mobile = (EditText)findViewById(R.id.mobile);
register = (Button)findViewById(R.id.Submit);
log_in = (Button)findViewById(R.id.Login);
//Adding Click Listener on button.
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checking whether EditText is Empty or Not
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
// If EditText is not empty and CheckEditText = True then this block will execute.
UserRegisterFunction(Username_Holder,Email_Holder, PasswordHolder, MobileHolder);
}
else {
// If EditText is empty then this block will execute .
Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,UserLoginActivity.class);
startActivity(intent);
}
});
}
public void CheckEditTextIsEmptyOrNot(){
Username_Holder = Username.getText().toString();
Email_Holder = Email.getText().toString();
PasswordHolder = Password.getText().toString();
MobileHolder = Mobile.getText().toString();
if(TextUtils.isEmpty(Username_Holder) || TextUtils.isEmpty(Email_Holder) || TextUtils.isEmpty(PasswordHolder) || TextUtils.isEmpty(MobileHolder))
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
public void UserRegisterFunction(final String Username, final String Email, final String Password, final String Mobile){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
Toast.makeText(MainActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
hashMap.put("username",params[0]);
hashMap.put("email",params[1]);
hashMap.put("password",params[2]);
hashMap.put("mobileno",params[3]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(Username,Email,Password,Mobile);
}
}
UserLoginActivity.java
public class UserLoginActivity extends AppCompatActivity {
EditText Email, Password;
Button LogIn ;
String PasswordHolder, EmailHolder;
String finalResult ;
String HttpURL = "http://codexpertise.com/codexpertise.com/apitest/login.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
public static final String UserEmail = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
Email = (EditText)findViewById(R.id.email);
Password = (EditText)findViewById(R.id.password);
LogIn = (Button)findViewById(R.id.Login);
LogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
UserLoginFunction(EmailHolder, PasswordHolder);
}
else {
Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
public void CheckEditTextIsEmptyOrNot(){
EmailHolder = Email.getText().toString();
PasswordHolder = Password.getText().toString();
if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
public void UserLoginFunction(final String email, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
if(httpResponseMsg.equalsIgnoreCase("Data Matched")){
finish();
Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);
intent.putExtra(UserEmail,email);
startActivity(intent);
}
else{
Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMap.put("username",params[0]);
hashMap.put("password",params[1]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
UserLoginClass userLoginClass = new UserLoginClass();
userLoginClass.execute(email,password);
}
}
HttpParse.java
public class HttpParse {
String FinalHttpData = "";
String Result ;
BufferedWriter bufferedWriter ;
OutputStream outputStream ;
BufferedReader bufferedReader ;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}

Login with incorrect information

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";

Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference

i have a school project. It was built by some previous developer. I am trying to run it. But i am getting NullPointerException. Here is my code:
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setToolbar();
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE1,OPERATION_NAME1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS1);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION1, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
int partitionSize =1;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
city=new ArrayList<String>();
for(int k=0;k<partitions.size();k++){
city.add(partitions.get(k).get(0));
}
callGetArea();
}
}.execute();
spcity= (Spinner) findViewById(R.id.spcity);
spcity.setOnItemSelectedListener(this);
sparea = (Spinner) findViewById(R.id.sparea);
sparea.setOnItemSelectedListener(this);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
rg = (RadioGroup) findViewById(R.id.gendergroup);
name= (EditText) findViewById(R.id.fname);
address=(EditText)findViewById(R.id.address);
contact= (EditText) findViewById(R.id.contact);
email= (EditText) findViewById(R.id.email);
weight= (EditText) findViewById(R.id.weight);
password= (EditText) findViewById(R.id.password);
cpass= (EditText) findViewById(R.id.cpassword);
earea= (Spinner) findViewById(R.id.sparea);
ecity= (Spinner) findViewById(R.id.spcity);
btnContinue= (TextView)findViewById(R.id.btncont);
bdate = (EditText) findViewById(R.id.bdate);
bdate.setInputType(InputType.TYPE_NULL);
bdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDateTimeField();
fromDatePickerDialog.show();
}
});
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isEmptyField(name)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Name", Toast.LENGTH_LONG).show();
} else if (isEmptyField(bdate)) {
Toast.makeText(RegistrationActivity.this, "Please Select Birthdate", Toast.LENGTH_LONG).show();
} else if (isEmptyField(address)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Address", Toast.LENGTH_LONG).show();
} else if (isEmptyField(weight)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Weight", Toast.LENGTH_LONG).show();
} else if (isEmptyField(contact)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Contact", Toast.LENGTH_LONG).show();
} else if (isEmptyField(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter E-Mail", Toast.LENGTH_LONG).show();
}else if (!isEmailPattern(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Valid E-Mail", Toast.LENGTH_LONG).show();
}else if (isEmptyField(password)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Password", Toast.LENGTH_LONG).show();
} else if (isEmptyField(cpass)) {
Toast.makeText(RegistrationActivity.this, "Please Confirm Password", Toast.LENGTH_LONG).show();
} else if (!isPasswordMatch(cpass,password)) {
Toast.makeText(RegistrationActivity.this, "Password doesn't match", Toast.LENGTH_LONG).show();
}
else {
if(isNetworkAvailable()) {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
resp = loginCall(email.getText().toString().trim());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.e("Response", resp + "");
dialog.dismiss();
if (resp == 1) {
UserClass userClass = new UserClass();
userClass.name = name.getText().toString();
userClass.dob = bdate.getText().toString();
int selectedId = rg.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
userClass.gender = radioButton.getText().toString();
userClass.address = address.getText().toString();
userClass.city = city.get(ecity.getSelectedItemPosition());
userClass.area = area.get(earea.getSelectedItemPosition()).city;
userClass.weight = weight.getText().toString();
userClass.contact = contact.getText().toString();
userClass.email = email.getText().toString();
userClass.password = password.getText().toString();
Log.e("name", userClass.name + "");
Log.e("dob", userClass.dob + "");
Log.e("gender", userClass.gender + "");
Log.e("address", userClass.address + "");
Log.e("city", userClass.city + "");
Log.e("area", userClass.area + "");
Log.e("weight", userClass.weight + "");
Log.e("contact", userClass.contact + "");
Log.e("email", userClass.email + "");
Log.e("password", userClass.password + "");
PrefUtils.setCurrentUser(userClass, RegistrationActivity.this);
Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity2.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Email Already Exist", Toast.LENGTH_LONG).show();
}
}
}.execute();
}
else
{
Toast.makeText(RegistrationActivity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar userAge = new GregorianCalendar(year,month,day);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please enter valid date",Toast.LENGTH_LONG).show();
}
}
private void callGetArea() {
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE2,OPERATION_NAME2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION2, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
final int partitionSize =2;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
area=new ArrayList<Area>();
for(int k=0;k<partitions.size();k++){
area.add(new Area(partitions.get(k).get(0),partitions.get(k).get(1)));
}
TimeSpinnerAdapter1 tspcity=new TimeSpinnerAdapter1(RegistrationActivity.this,city);
spcity.setAdapter(tspcity);
spcity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayList<Area> tempList=new ArrayList<Area>();
for(int i=0;i<area.size();i++){
Log.e("city............",area.get(i).area+"");
if(area.get(i).area.equalsIgnoreCase(city.get(position))){
tempList.add(area.get(i));
}
}
TimeSpinnerAdapter tsparea = new TimeSpinnerAdapter(RegistrationActivity.this, tempList);
sparea.setAdapter(tsparea);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}.execute();
}
private void setDateTimeField() {
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar userAge = new GregorianCalendar(year,monthOfYear,dayOfMonth);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please Enter Valid Date",Toast.LENGTH_LONG).show();
} else {
bdate.setText(dateFormatter.format(userAge.getTime()));
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
public boolean isEmptyField(EditText param1) {
boolean isEmpty = false;
if (param1.getText() == null || param1.getText().toString().equalsIgnoreCase("")) {
isEmpty = true;
}
return isEmpty;
}
private void setToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Register");
setSupportActionBar(toolbar);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class TimeSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<Area> asr;
public TimeSpinnerAdapter(Context context,ArrayList<Area> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position).city);
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i).city);
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public static boolean isEmailPattern(EditText param1) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(param1.getText().toString()).matches();
}
public static boolean isPasswordMatch(EditText param1, EditText param2) {
boolean isMatch = false;
if (param1.getText().toString().equals(param2.getText().toString())) {
isMatch = true;
}
return isMatch;
}
public class TimeSpinnerAdapter1 extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<String> asr;
public TimeSpinnerAdapter1(Context context,ArrayList<String> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position));
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i));
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public int loginCall(String c1)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo p1=new PropertyInfo();
p1.setName("email");
p1.setValue(c1);
p1.setType(String.class);
request.addProperty(p1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response=null;
try
{
httpTransport.debug=true;
httpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
}
catch (Exception ex)
{
// ex.printStackTrace();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
//displayExceptionMessage(ex.getMessage());
//System.out.println(exception.getMessage());
}
return Integer.parseInt(response.toString());
}
I am getting NullPointerException on response= envelope.getResponse();
My error is following:
Process: com.nkdroid.blooddonation, PID: 16820
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference
at org.ksoap2.serialization.SoapSerializationEnvelope.getResponse(SoapSerializationEnvelope.java:513)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:146)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:120)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
Can anyone help me with that?
I know code is a mess. But any help will be appreciated.
Thanks! :)
Make sure you have the same name as property in your service and android parameters, for example request.addProperty("name",name) in the WebService public class Login(String name)

app crashing when trying to connect Internet

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);
}
}
}
}
}

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`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;
private LoginBean loginBean;
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);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
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);
Utility.hideSoftKeyboard(LoginActivity.this);
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);
Utility.hideSoftKeyboard(LoginActivity.this);
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);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
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"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

Categories

Resources