I wanna upadate recyclerview child item when itself clicked.It takes the data from server and updates it self. kindly provide any solution for this scenario.Here i have tried as i know but it is not updating.
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
SQLiteHandler db = new SQLiteHandler(context);
HashMap<String, String> user = db.getUserDetails();
String tag_string_req = "req_login";
final String uid = user.get("uid");
Log.d("hello", uid);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.Upvote, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String upvote_no = jObj.getString("upcount");
String text = "Upvoted " + upvote_no;
((TextView) v).setText(text);
//Log.d("resp", upvote);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(context, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("qries_user_id", uid);
params.put("qries_answer_id", answered_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
});
In the above code i am trying to taking response from Json and updating to self child item as ((TextView) v).setText(text); but it is not updating.Thanks in Advance!
Try to cast your clicked view in TextView
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).setText("something");
}
});
Related
I am making registration activity in android with volley but i get some error in post method please help
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
I am using volley:library-aar:1.0.0
And AppConfig.java
public class AppConfig {
public static String URL_REGISTER = "";
}
Error is
There is no applicable constructor to '(int.java.lang.string, com.andro.login.RegisterActivity.(anonymous), com.andro.login.RegisterActivity.(anonymous))'
Any solution for this prob?
I am sending data from an android client to a grails backend. I want two things to happen when data is successfully posted:
A toast with some of the params I have posted(In this case I want
only name)
An intent to open another activity.
However with my code, the parameters are posted successfully to the db but the toast and the intent do not happen.
Here is my code:
*/
private void registerUser(final String chname, final String chdesc, final String patientID) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Configs.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String chname = user.getString("name");
String chdesc = user.getString("description");
String patientID = user.getString("patient");
Toast.makeText(getApplicationContext(), "User successfully registered.", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(AddChronics.this,
ChronicsFragment.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to activity_register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", chname);
params.put("description", chdesc);
params.put("patient", patientID);
params.put("action", "chronicAdd");
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Note: The API works just fine. I have checked and the params are successfully saved to the db.
Your code looks fine, the only thing that might prevent the intent and toast from happening is if your code gets cought by an excepetion here:
catch (JSONException e) {
e.printStackTrace();
}
Caused by one of these guys:
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
Did you check that?
Have you tried using activity context instead of applicationContext?
I want to make a POST request to a rest api with body x-www-form-urlencoded parameters. I have tried the following code but I am getting error code 400.
I have been trying to debug this from hours but getting same response. Any help will be appreciated.
public class LoginFragment extends Fragment {
private static final String TAG = "LoginFragment";
EditText mUsername, mPassword;
Button mLogin;
String url = "abc";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login, container, false);
mUsername = (EditText) rootView.findViewById(R.id.login_name_edit_text);
mPassword = (EditText) rootView.findViewById(R.id.login_password_edit_text);
mLogin = (Button) rootView.findViewById(R.id.login_button);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = mUsername.toString();
String password = mPassword.toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
checkLogin(username, password);
} else {
Toast.makeText(getContext(), "Please enter the credentials!", Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
private void checkLogin(final String username, final String password) {
// Tag used to cancel the request
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Launch main activity
Intent intent = new Intent(getActivity(),
MainActivity.class);
startActivity(intent);
getActivity().finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MySingleton.getInstance(getContext()).addToRequestQueue(strReq);
}
}
it was a silly mistake
I wrote mUsername.toString() instead of mUsername.getText()
Im using Restful Java to parse data json with POST method and Volley in android. When I try to insert data from Advanced REST Client, it insert data into db success, but in Android, when I insert data and see that it happen an exception as below:
My Restful (UPDATED):
#Path("/bookticket")
public class BookServiceCalled {
#POST
#Path("/json")
#Produces("application/json;charset=utf-8")
#Consumes("application/x-www-form-urlencoded") // MediaType.APPLICATION_JSON
public static void bookFromUser(#QueryParam("fullname") String fullname,
#QueryParam("birthday") Date birthday,
#QueryParam("address") String address) throws Exception {
Connection connection = null;
PreparedStatement statement = null;
try {
// Config connect mydb
String query = "INSERT INTO order "
+ "(fullname, birthday, address) VALUES "
+ "(?,?,?) ";
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, fullname);
statement.setDate(2, birthday);
statement.setString(3, address);
statement.executeUpdate();
System.out.println("Work !");
}
catch (Exception e) {
// TODO Auto-generated catch block
if (connection != null) {
connection.close();
}
throw e;
}
finally {
if (connection != null) {
connection.close();
}
}
}
}
My activity class:
private static final String URL_BOOK = "http://192.168.1.221:9999/bookticket_service/bookticket/json";
EditText fullname, birthday, address;
fullname = (EditText) findViewById(R.id.fullname);
birthday = (EditText) findViewById(R.id.birthday);
address = (EditText) findViewById(R.id.address);
btnBook = (Button) findViewById(R.id.btnBook);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL_BOOK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> parameter = new HashMap<String, String>();
parameter.put("Content-Type", "application/json; charset=utf-8");
parameter.put("fullname", fullname.getText().toString());
parameter.put("birthday", birthday.getText().toString());
parameter.put("address", address.getText().toString());
return parameter;
}
};
// volley saves the response in its cache and this behavior may cause some strange problem
// request.setShouldCache(false);
requestQueue.add(request);
}
});
Logcat:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'fullname' cannot be null
How to fix the exception, thanks for the help
I get an error when I make multiple volley requests.
First, I am requesting login and it works fine. After the login process, the main activity opens in the application. When I make a new request here, the request is added to the queue. But the request is not executed. what is the reason of this?
This code is login function:
private void LoginUser(final String email, final String password) {
String tag_string_req = "request_register";
pDialog.setMessage("Giriş Yapılıyor ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
int userId = user.getInt("UserId");
int uId = user.getInt("UId");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("UserId", userId);
intent.putExtra("UId", uId);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This code is get datas about user at after login function:
public void Sync(final Context context, final int uId)
{
String tag_string_req = "request_syncUser";
db1 = new Database(context);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//gelen tüm verileri local db ye at
try {
SQLiteDatabase db = db1.getWritableDatabase();
JSONObject jObj = new JSONObject(response);
JSONArray responseUser = jObj.getJSONArray("user");
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if(!error) {
for(int i=0; i<responseUser.length(); i++)
{
JSONObject user = responseUser.getJSONObject(i);
String u_name = user.getString("Name");
String u_surname = user.getString("Surname");
String u_email = user.getString("Email");
String u_password = user.getString("Password");
String u_isLogin = user.getString("isLogin");
String u_isSync = user.getString("isSync");
int u_uId = user.getInt("UId");
ContentValues cv = new ContentValues();
cv.put("Name", u_name);
cv.put("Surname", u_surname);
cv.put("Email", u_email);
cv.put("Password", u_password);
cv.put("isLogin", u_isLogin);
cv.put("isSync", u_isSync);
cv.put("UId", u_uId);
db.insertOrThrow("user", null, cv);
Toast.makeText(context, message ,Toast.LENGTH_LONG).show();
Toast.makeText(context, u_name + u_surname,Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uId", String.valueOf(uId));
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
Well we need to see your code?
That said my guess is you are not creating / accessing your queue in a singleton pattern. Complete guess. Always always always post code.