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
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 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.
I want to pass the Spinner value to php and get some result and display into my TextView. when i use Toast to display the Selected value its working perfect.but while pass the value to the php file i am struck. I tried some ways. can some to fix my problem.
java file:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this for hide title bar
setContentView(R.layout.sales_order);
fg.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
if(goods_name1.getSelectedItem() !=null && goods_name1.getSelectedItem() !=""){
// WebServer Request URL
String serverURL = "http://IP/fs/getProductOneStock.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Sales_Order.this);
String data ="";
int sizeData = 0;
TextView pro_stock1 = (TextView)findViewById(R.id.tv_stock1);
Spinner fgStock = (Spinner)findViewById(R.id.spinner1);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+fgStock.getSelectedItem();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
pro_stock1.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
pro_stock1.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Finish_goods_mas");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String Stock1 = jsonChildNode.optString("Finish_goods_mas").toString();
OutputData += Stock1;
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
my php file
<?php
require "db_config.php";
$Goods_name=$_POST['Goods_name'];
$sql = "select goods_min_level from Finish_goods_mas where Goods_name='".$Goods_name."'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
//echo $row['cus_id']."<br />";
$json['Finish_goods_mas'][]=$row;
}
sqlsrv_free_stmt( $stmt);
echo json_encode($json);
?>
after make changes of doInBackground and onPreExecute() the Spinner value not pass to php file also i cannot get back result from php
When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
so textView.setText(strOrderNo); do it in onPostExecute(Result) override method
This question already has answers here:
Only the original thread that created a view hierarchy can touch its views ERROR
(2 answers)
Closed 8 years ago.
I have an AsyncTask class inside my main activity. This class parses a JSON Object and then it sets the texts on some UI Components like TextViews, EditTexts etc. The problem is that when it sets the text on the first TextView then it stops. It will not give an error but the "Only the original thread that created a view hierarchy can touch its views" exception which actually means that you cannot affect any UI components through the AsynTask. I read that this could be done through a Runnable thread but i am not familiar how this can be done in my code. Any suggestions will be more than welcomed!!Thank you all!!
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
TextView txt_class = (TextView) findViewById(R.id.txt_class);
TextView v_points = (TextView) findViewById(R.id.txt_points);
//EditText name = (EditText) findViewById(R.id.fname);
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/consumer.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
// Convert response to String
//String result = EntityUtils.toString(response.getEntity());
// TEST
postResponse = EntityUtils.toString(resEntity).trim();
// CONVERT RESPONSE STRING TO JSON Object
JSONObject json = new JSONObject(postResponse);
// Get the JSONArray "Consumer"
JSONArray ja = json.getJSONArray("Consumer");
//List<String> detailsList = new ArrayList<String>();
// Creating the array that will hold the json items
String[] info = new String[ja.length()];
// Loop through all fields
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("userid");
String fname = c.getString("userfullname");
String tel1 = c.getString("tel1");
String email = c.getString("email");
String address = c.getString("address");
String county = c.getString("county");
String country = c.getString("country");
String rpoints = c.getString("RedeemPoints");
String level = c.getString("Level");
Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints + "\n"+ "Level: "+level);
txt_class.setText("Domotel "+ level+" Member");
v_points.setText("TestTestTest");
}
//Log.v(TAG, "Testing response: " + postResponse);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
You have to update your UI in the onPostExecute of your AsyncTask.
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.