The program gets input rollno and name and displays the address and marks based on it. I get the output for marks and address as null instead of the value stored in the databse. The PHP code works fine. >
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private EditText editText2;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String rollno = editText.getText().toString().trim();
if (rollno.equals("")) {
Toast.makeText(this, "Please enter an rollno", Toast.LENGTH_LONG).show();
return;
}
String name = editText2.getText().toString().trim();
if (name.equals("")) {
Toast.makeText(this, "Please enter an name", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = http://192.14.6.113/getData.php?rollno="+rollno+" & name="+name;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
tring address="";
String marks = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
address = collegeData.getString(Config.KEY_ADDRESS);
marks = collegeData.getString(Config.KEY_MARKS);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Address:\t" +address+ "\nMarks:\t"+ marks);
}
#Override
public void onClick(View v) {
getData();
}
}
Related
I am creating a simple android app to upload data to mysql server db, but shows error as string cannot be converted to JSON Object.
Can i make it for filtering vulgar words too?
This is for my android app, if this works fine i will use it for uploading words and meanings for my dictionary
I tried other solution.
public class MainActivity extends Activity {
private EditText etName, etMobile, etAddress;
private Button btnSubmit;
private ProgressDialog pDialog;
private JSONObject json;
private int success = 0;
private HTTPURLConnection service;
private String strname = "", strMobile = "", strAddress = "";
//Initialize webservice URL
private String path = "https://meiteiwords.000webhostapp.com/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etMobile = (EditText) findViewById(R.id.etMobile);
etAddress = (EditText) findViewById(R.id.etAddress);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
//Initialize HTTPURLConnection class object
service = new HTTPURLConnection();
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etName.getText().toString().equals("") && !etMobile.getText().toString().equals("")) {
strname = etName.getText().toString();
strMobile = etMobile.getText().toString();
strAddress = etAddress.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams = new HashMap<String, String>();
postDataParams.put("name", strname);
postDataParams.put("mobile", strMobile);
postDataParams.put("address", strAddress);
//Call ServerData() method to call webservice and store result in response
response = service.ServerData(path, postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (success == 1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
here is my php code shows warning :
https://pastebin.com/P50EWbbR
https://pastebin.com/Aut7fFq2
You got type casting error because you try to convert String into JSONObject. You failed to sent your response as JSONObject.
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 use volley library on android code
i want to know check if my table has been updated or inserted then wanted to do it(A), otherwise it(B)
for example if my table updated or inserted then send (A)sms otherwise (B)toast
its my activity code:
public class DeviceAddActivity extends AppCompatActivity implements View.OnClickListener {
private static final String REGISTER_URL = "http://192.168.43.190/entezam/addphone.php";
public static final String KEY_CUSTNAME = "Customer_non";
public static final String KEY_PHONENAME = "Phone_Name";
public static final String KEY_IMEI = "IMEI";
private EditText editTextName;
private EditText editTextPhoneName;
private EditText editTextIMEI;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_add);
editTextName = (EditText) findViewById(R.id.editTextcustname);
editTextPhoneName = (EditText) findViewById(R.id.editTextphonename);
editTextIMEI= (EditText) findViewById(R.id.editTextimei);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String Customer_non = editTextName.getText().toString().trim();
final String Phone_Name = editTextPhoneName.getText().toString().trim();
final String IMEI = editTextIMEI.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(DeviceAddActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceAddActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_CUSTNAME,Customer_non);
params.put(KEY_PHONENAME,Phone_Name);
params.put(KEY_IMEI,IMEI);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
}
and its my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Phone_Name = $_POST['Phone_Name'];
$Customer = $_POST['Customer_non'];
$IMEI = $_POST['IMEI'];
require_once('dbConnect.php');
$sql = "INSERT INTO phone_in (Phone_Name,Customer_non,IMEI) VALUES ('$Phone_Name','$Customer','$IMEI')";
if(mysqli_query($con,$sql)){
echo "Successfully Registered";
}else{
echo "Could not register";
}
}else{echo 'error';}
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();
}
I am sending details to be stored in a database using a web service using KSOAP.There is nothing wrong with the web service it works fine. This code worked when i didn't user AsyncTask class. I am new to android and this is the first time i tried using the AsyncTask class and it does not work. I have attached the log cat errors, something is wrong with the doinbackround method. What am I doing wrong? Please help
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:54714/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());
if(result == '1')
{
return "Registered";
}
else
{
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(result=="Registered")
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result =="Not Registered")
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
////Edited
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:54714/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Log.d("work","work");
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());
if(result == 1)
{
Log.d("reg","reg");
return "Registered";
}
else
{
Log.d("no","no");
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("tag","onpost");
if(result!=null)
{
if(result.equals("Registered"))
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result.equals("Not Registered"))
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
You're calling
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
inside doInBackground(), which not running in UI thread. That causing the problem.
Try this:
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
});
}
or move the Toast.makeText to onPostExecute() method, which running in UI thread
This is because you are calling Toast in the doInBackground(). Whatever UI in doInBackground will make the looper() exception. so try to make the UI in the PostExecute() in AsynTask
as
#Override
protected void onPostExecute(String result) {
Toast.makeText(Registration.this, "You have been registered Successfully",Toast.LENGTH_LONG).show();
}
}
It may helpful to you..
you should not compare strings using ==.
protected void onPostExecute(String result) {
if(result=="Registered")
That could be the reason behind the unexpected behavior. Try using something like
result.equals("registered")
read this
Try this....
Always keep the UI work in UI thread, and Non-UI work in Non-UI thread.
doInBackground is a Non-UI thread, so you can NOT post anything on the UI thread
from this.
The Toast statement is the problem in doInBackgroud, move it to postExecute, which is
working on UI thread.
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();