I am developing and I want to show user login or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e login success or login failed message). How do I do this?
How do I parse json data in this?
Please suggest me!!
// Following is response from server shows inside Logcat
{
"login": [
{
"sessionid": 12973,
"responsetypes": "success"
}
]
}
// Following is my code
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendGetReqButton;
TextView tv_forgot;
Button register;
Toolbar toolbar;
private boolean loggedIn = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tv_forgot= (TextView)findViewById(R.id.tv_forgot);
tv_forgot.setOnClickListener(this);
usernameEditText = (EditText) findViewById(R.id.ed_email);
passwordEditText = (EditText) findViewById(R.id.ed_passowrd);
register = (Button) findViewById(R.id.btn_reg);
sendGetReqButton = (Button) findViewById(R.id.btn_login);
sendGetReqButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_login){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
}
else {
Toast.makeText(LoginActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
}
}
private void connectWithHttpGet(String userID, String password) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(result.equals("success"))
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else {
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
}
You can do like this.
In the onPostExecute() method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("login");
JSONObject jsonObject1 = login.getJSONObject(0);
// edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
String responsetypes = jsonObject1.optString("responsetypes");
// edited
String sessionid = jsonObject1.getString("sessionid");
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetypes, "failure")) {
// edited
String message = jsonObject1.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for example method get error response use volley.
private void getLogin() {
JSONObject param = new JSONObject();
try {
param.put("username", username.getText().toString());
param.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("login");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("sessionid>> ", jsonObject.getString("sessionid"));
}
dissmissPDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error >> ", error.toString());
streror = error.toString();
dissmissPDialog();
}
}
);
normal.add(jsonObjectRequest);
}
Update your onPostExecute() method like this.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject1 = new JSONObject(result);
JSONArray jsonArray = jsonObject1.getJSONArray("login");
JSONObject jsonObjectLogin = jsonArray.getJSONObject(0);
String response = jsonObjectLogin.getString("responsetypes");
Toast.makeText(getApplicationContext(), +response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Let me know this is working or not.
Related
I am developing and I want to show user register or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e registration success or registration failed message).I am trying to parse response but logcat shows message is "org.json.JSONException: No value for responsetypes"
How do I parse json data in this? Please suggest me!!
I have do changes as per suggested!
What else i have to do here?
// Following is response from server shows inside Logcat
{"signup":[
{"sessionid":0,
"responsetype":"failure",
"message":"Username emailid already register."
}
]
}
// Following is my code
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextfName;
private EditText editTextlName, editTextDid, editTextBd;
private EditText editTextPassword;
private EditText editTextEmail;
TextView txtBirthDate;
private Button buttonRegister;
Button buttonBdate;
String selected_date="";
int mYear, mMonth, mDay;
Calendar myCalendar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextfName = (EditText) findViewById(R.id.editTextfName);
editTextlName = (EditText) findViewById(R.id.editTextlName);
// editTextDid = (EditText) findViewById(R.id.editTextdid);
editTextBd = (EditText) findViewById(R.id.editTextbdate);
// txtBirthDate = (TextView) findViewById(R.id.txtBdate);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.buttonRegister){
// Get the values given in EditText fields
String firstname = editTextfName.getText().toString();
String lastname = null;
String emailaddress = editTextEmail.getText().toString();
String birthdate = null;
String password = editTextPassword.getText().toString();
String deviceid = null;
System.out.println("Givennames is :" + firstname + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(firstname,lastname,emailaddress,birthdate,password,deviceid);
}
}
private void connectWithHttpGet(String firstname, String lastname, String emailaddress, String birthdate, String password, String deviceid) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
private Context context;
private HttpGetAsyncTask(Context context){
this.context=context;
}
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramFname = params[0];
String paramLname = params[1];
String paramEmail = params[2];
String paramBirthdate = params[3];
String paramPassword = params[4];
String paramDeviceid = params[5];
System.out.println("userID" + paramFname + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/signUp?firstname="+paramFname+"&lastname="+paramLname+"&emailid="+paramEmail+"&birthdate="+paramBirthdate+"&password="+paramPassword+"&deviceid="+null);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("signup");
JSONObject jsonObject1 = login.getJSONObject(0);
String sessionid = jsonObject1.getString("sessionid");
String responsetype = jsonObject1.getString("responsetype");
String message = jsonObject1.getString("message");
Log.i("response",responsetype);
// Toast.makeText(RegisterActivity.this, responsetype, Toast.LENGTH_LONG).show();
if (TextUtils.equals(responsetype, "success")) {
Toast.makeText(RegisterActivity.this, "success !!" , Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetype, "failure")) {
Toast.makeText(RegisterActivity.this, "failed......!!", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(RegisterActivity.this, "Invalid...", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this);
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(firstname,lastname,emailaddress,birthdate,password,deviceid);
}
}
Your json has a key called responsetype
whereas you are using responsetypes in your code
String responsetypes = jsonObject1.getString("responsetypes");
remove the "s" and it should work.
String responsetypes = jsonObject1.getString("responsetype");
Also update your HttpGetAsyncTask class with below parameter and constructor. So add below code in your HttpGetAsyncTask
private Context context;
//in constructor:
public HttpGetAsyncTask(Context context){
this.context=context;
}
Then to initialize this calls use code as below -
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this);
instead of -
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
and to show toast use -
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(context, "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Invalid...", Toast.LENGTH_LONG).show();
}
This is because AsyncTask doesn't inherit context and hence UI elements cannot be called using getApplicationContext() in AsyncTask
add an "s" to responsetype because in your json
{"signup":[
{"sessionid":0,
"responsetype":"failure",
"message":"Username emailid already register."
}
]
}
I am developing an app, in this i create login of user but i want to use session using sharedpreferences inside this login. How do i implement session in this?
Following is my code please suggest me, how do i do inside my code?
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendGetReqButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText = (EditText) findViewById(R.id.editTextUserName);
passwordEditText = (EditText) findViewById(R.id.editTextPassword);
sendGetReqButton = (Button) findViewById(R.id.button);
sendGetReqButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
Intent in = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(in);
}
}
private void connectWithHttpGet(String userID, String password) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(!result.equals(null))
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else if(result.equals("failure")){
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
}
You can create SharedPreferences key value for storing the logged user credentials in the onPostExecute method
SharedPreferences spref = getSharedPreferences("MySpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("User", usr);
editor.commit();
Some modifications added in your code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText = (EditText) findViewById(R.id.editTextUserName);
passwordEditText = (EditText) findViewById(R.id.editTextPassword);
sendGetReqButton = (Button) findViewById(R.id.button);
sendGetReqButton.setOnClickListener(this);
// Regitration Button is required
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
if (userID!=null && password!=null) {
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
}
// Here Registration need to be in different button
// Intent in = new Intent(LoginActivity.this,RegisterActivity.class);
// startActivity(in);
}
}
private void connectWithHttpGet(String userID, String password) {
// Here you can check newtork connection is ok or not
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String usr;
protected void onPreExecute() {
// Here you can use loading animation
}
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
usr=paramUsername;
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(!result.equals(null))
// Here you do the logic
// if the response is JSON then you have use json Parser
// JSONObject jObj = new JSONObject(result);
// if user is valid then you can store it in SharedPreferences
// response maybe different types so you have check it vaild or not
SharedPreferences spref = getSharedPreferences("MySpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("User", usr);
editor.commit();
//YOU CAN NAVIGATE TO NEW PAGE
// Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else if(result.equals("failure")){
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
Hope this changes works
please have a look at my basic Android-Webserver code.
Data should from Android smartphone should be sent to a webserver, webserver should put data in database and then give the query:
{"query_result":"SUCCESS"}
(when i access the server-side script via browser i get this JSON-message, also the data is insterted into database)
The problem is that my app doesn't parse the JSON response correct or even doesn't get any response?
My code so far:
http://bits.works/view/466210bb
The code shows "Error parsing JSON data" on Android screen.
Call of method:
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
new SignupActivity(AndroidGPSTrackingActivity.this).execute(Double.toString(latitude), Double.toString(latitude), Double.toString(longitude), Double.toString(longitude), Double.toString(latitude));
Class with method:
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
String userName = arg0[1];
String passWord = arg0[2];
String phoneNumber = arg0[3];
String emailAddress = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://qqqqqtech/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Check the returned value from doInBackground before the line
String query_result = jsonObj.getString("query_result");
This is because doInBackground might have caught an exception and returned that instead of a valid response. So, make a Toast with jsonStr before trying to parse it to see what it contains.
I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.
I have created a separate class for Asynchronous task. How can I pass the string value to that Asynchronous task class? Please refer my code below.
In Main class to call Asynchronous task class
String product_id,av_quantity;
Stock_updatetask = new Stock_update();
Stock_updatetask.execute(product_id,av_quantity);
How to send String product_id,av_quantity values to Asynchronous task Class
Asynchronous task Class
public class Stock_update extends AsyncTask<String, Void, String> {
JSONObject json = new JSONObject();
JSONArray jsonarray;
protected String doInBackground(String... params) {
try {
// checkInternetConnection();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),20000);
HttpConnectionParams.setSoTimeout(client.getParams(), 20000);
HttpResponse response;
HttpPost post = new HttpPost("http://www.name.in/cakefoodnew/customer/stockUpdate?json=");
/*json.put("submenu_id", "" + product_id);
json.put("available_quantity", "" + av_quantity);*/
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
// get a data
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
// Log.v("id", ""+a);
try {
jsonarray = new JSONArray("[" + a + "]");
json = jsonarray.getJSONObject(0);
//stock_update = (json.getString("Success"));
} catch (Exception e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
// Json response
private String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
get product_id,av_quantity values inside doInBackground method as :
//....your code here...
json.put("submenu_id", "" + params[0]); //<<<< get product_id
json.put("available_quantity", "" + params[1]); //<<< get av_quantity
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
because doInBackground method parameter is Varargs you can get more about Varargs here
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
or second way is you can pass both values by creating an Stock_update constructor as :
public class Stock_update extends AsyncTask<String, Void, String> {
String product_id,av_quantity;
public Stock_update(String product_id,String av_quantity){
this.product_id=product_id;
this.av_quantity=av_quantity;
}
//your code here
}
pass both values at time of object creation of Stock_update class :
Stock_updatetask = new Stock_update(product_id,av_quantity);
now you are able to use product_id,av_quantity in whole Stock_update class including doInBackground
See this code
DownloadingProgressTask downloadingProgressTask = new DownloadingProgressTask(
Utilities.arrayRSSDownload.get(0).getUrl(),
mainprogressbar, Utilities.arrayRSSDownload
.get(0).getTitle());
downloadingProgressTask.execute();
And then in class
private class DownloadingProgressTask extends
AsyncTask<String, Integer, Boolean> {
String fileName;
ProgressBar progressbar;
/** progress dialog to show user that the backup is processing. */
public DownloadingProgressTask(String url1, ProgressBar progress,
String filetitle) {
urllink = url1;
fileName = filetitle;
progressbar = progress;
}
protected void onPreExecute() {
mainprogressbar.setProgress(0);
progressbar.setProgress(0);
myDatabase.updateDownloadStatus(fileName, 2);
// Updating the home screen list
setListData();
}
--- rest of code