My Data is Not Stored in Database - android

I am making a simple register app where user sign up and data store in the My Mydatabase like usename, name, age, passsword
I already created database table in phpMyAdmin and I uploaded Register.php file into my server I check Register.php file their is no error it works great (I use postman app that act as app to send sign up details to the server it actually work my database is storing the values send by the postman app but when I use android app and sign up data is not storing in my database)
They should be some mistake in my code but error is not showing I take entire day to solve the problem not still not found.
I am referring to this tutorial https://www.youtube.com/watch?v=T7Z4GVFaT4A&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka&index=4
I am using volley networking library in my gradle file
Here Register Activity where user enter username, name, age, password is store and send back to another activity to send server
It is linked with xml file whre user can sign up
public class RegisterActivity extends AppCompatActivity {
EditText username , name , pass , age;
Button r_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = (EditText)findViewById(R.id.username_et);
name = (EditText)findViewById(R.id.name_et);
pass = (EditText)findViewById(R.id.pass_et);
age = (EditText)findViewById(R.id.age_et);
r_button = (Button)findViewById(R.id.register_button);
r_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usname = username.getText().toString();
String nam = name.getText().toString();
String password = pass.getText().toString();
int ages = Integer.parseInt(age.getText().toString());
Response.Listener<String> responselistner = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success)
{
Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
startActivity(intent);
//after successfull sign up it redirect to login page
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Registration failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(nam, usname,ages,password , responselistner);
RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
requestQueue.add(registerRequest);
}
});
}
}
Here is my class RegisterRequest
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL ="http://fgeeges.esy.es/Register.php";
private Map<String, String> params;
public RegisterRequest(String name , String username , int age , String password , Response.Listener<String> listener)
{
super(Method.POST, REGISTER_REQUEST_URL , listener ,null);
params = new HashMap<>();
params.put("name ",name);
params.put("username",username);
params.put("age" ,age+"");
params.put("password",password);
}
}

Add
#Override
public Map<String, String> getParams(){
return params;
}
in the RegisterRequest Class.

Related

Android Studio: XmlRpcClientException Failed to parse servers response: Unexpected non-whitespace character data

So i'm traying to connect my application with an odoo database in android studion with an odoo External API "XML-RPC" to get data from the database, I was able to connect and i get the user Id successfuly, i was also able to search and create normaly, but when i'm trayin to read any thing from the database, this exception keep showing. and i can't find any thing that he can help me.
So please is there any one who can tell me where i am mestaking ?
This is my code:
public class MainActivity extends AppCompatActivity {
final String db = "BTP_p",
username = "admin",
password = "_chantier";
final String url ="http://sogesi.hopto.org";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DemoTask().execute(url);
}
class DemoTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(final String... url) {
final XmlRpcClient client = new XmlRpcClient();
final XmlRpcClientConfigImpl common_config = new XmlRpcClientConfigImpl();
try {
//Testé l'authentification
common_config.setServerURL(
new URL(String.format("%s/xmlrpc/2/common", url)));
int uid = (int)client.execute(
common_config, "authenticate", asList(
db, username, password, emptyMap()));
Log.d("result", "*******************************************************************");
Log.d("uid = ", Integer.toString(uid));
//Testé la liste des recordes d'une table
final XmlRpcClient models = new XmlRpcClient() {{
setConfig(new XmlRpcClientConfigImpl() {{
setServerURL(new URL(String.format("%s/xmlrpc/2/object",url)));
}});
}};
final List id = asList((Object[])models.execute(
"execute_kw", asList(
db, uid, password,
"project.chantier", "search",
asList(asList(
asList("state", "=", "en_cour"))),
new HashMap() {{
put("limit", 1);
}}
)));
//this is the ligne where the exception is rising
final Map record = (Map)((Object[])models.execute(
"execute_kw", asList(
db, uid, password,
"project.chantier", "read",
asList(id)
)
))[0];
return (Integer) uid;
} catch (MalformedURLException e) {
Log.d("MalformedURLException", "*********************************************************");
Log.d("MalformedURLException", e.toString());
} catch (XmlRpcException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO: do something with the feed
}
}
}
This is the exception
In my case I had to download and import this three libraries :
exist-dependency-ws-commons-util-1.0.2.jar
xmlrpc-client-3.1.jar
xmlrpc-common-3.1.jar

Android - Use Broadcast Receiver to reload activity

I am developing an android application and I have one activity which shows all the tables in a restaurant. Within this activity, there is a method to change the table color (the table is just a button) based on whether a customer is at the table.
On the customer's screen, when they select their table, my MYQSL database is updated and the user is now assigned to the table.
Now, when I go to open the map screen (note: this is used by waiters on the app, it cant be accessed by customers), the table will be a different color (it checks the table status in the db, if the table is assigned it is a different color).
However, the only way to get the updated map is by reloading the map activity. I want the map activity to update automatically using a BroadcastReceiver() but I am struggling to find a tutorial on how to implement this. When a customer clicks a table to assign themselves to it, I want the broadcast to be sent, automatically reloading the map activity... Is this possible? And if so, how do I implement it?
EDIT: The waiter and customer are using the same application but on different devices
The ChooseTable activity has an on click listener for each table which results in the following method being called:
private void assignUserToTable(final int table, final String userid) {
String url = "hidden";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("success")) {
Toast.makeText(ChooseTable.this, "Welcome!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ChooseTable.this, "Oops, something went wrong!", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ChooseTable.this, "Error! " + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("table_id", String.valueOf(table));
params.put("user", userid);
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
The waiter map view looks has the following method which checks the table status on the activity being loaded:
private void checkTables(){
String url = "hidden";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("toggles");
if(success.equals("1")){
for(int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String tableid = object.getString("tableid");
if(Tbl1.getTag().equals(tableid)){
Tbl1.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl2.getTag().equals(tableid)){
Tbl2.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl3.getTag().equals(tableid)){
Tbl3.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl4.getTag().equals(tableid)){
Tbl4.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl5.getTag().equals(tableid)){
Tbl5.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl6.getTag().equals(tableid)){
Tbl6.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl7.getTag().equals(tableid)){
Tbl7.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
} else if(Tbl8.getTag().equals(tableid)){
Tbl8.setBackgroundColor(ContextCompat.getColor(WaitingStaffMapScreen.this, R.color.tableReq));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(WaitingStaffMapScreen.this, "Oops, something went wrong!", Toast.LENGTH_LONG).show();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(WaitingStaffMapScreen.this, "Error! " +error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("table_id", "0");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
Essentially I want some means of reloading the map screen activity when a table button has been clicked.
Since everything is running on separate devices, what I would do is implement firebase cloud messaging:
https://firebase.google.com/docs/cloud-messaging/android/client
When the application is started, the device receives a token.
When the device receives this token, you will POST it to your database(assuming you have a table of devices) under a new column(ie: FirebaseToken) for that device row.
When the table status is updated(ie: a user selects a table), and that reaches out to the server, you will have a query that goes through each device registered to the business, and sends a push notification.
Then on the android app, you will have a firebase service running that receives the push notification(ie:)
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
NotificationManager notificationManager;
#Override public void onMessageReceived(RemoteMessage remoteMessage)
{
Map<String,String> data = remoteMessage.getData();
if (data.get("title").equals("Update Tables")) {
//Call logic to update the adapter
}
}
}
Very general gist of it. Relatively easy to implement. Any questions, I can do my best to clarify.
As the below comment said, using group messaging is best. I didn't know how many devices each business would have, so was trying to keep it as simple as possible.
Here is a server side example. This will simply send a push notification to the phone, and will be received in the FirebaseMessagingService class you extended.
public bool SendMessage(string firebaseTokenId, FirebaseMessages type)
{
httpWebRequest = (HttpWebRequest)WebRequest.Create("http://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", "your key");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var messageToSend = new Message()
{
to = firebaseTokenId,
data = new DataPayload()
{
title = firebaseMessages[type].title,
message = firebaseMessages[type].body,
}
};
string json = JsonConvert.SerializeObject(messageToSend, Formatting.Indented);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
public enum FirebaseMessages
{
UpdateTables
}
public class Message
{
public DataPayload data {get;set;}
public string to { get; set; }
}
public class DataPayload
{
public string title { get; set; }
public string message { get; set; }
}
//on the on receive, this is a datapayload(not notification), so no push intent will ever be shown, hence you can leave the body null.
firebaseMessages.Add(FirebaseMessages.MessageReceived, new FirebaseMessage() { title = "Table Update", body = ""});

How to Access log in credentials in another activity

Here iam working with web services i need to access username and password variabes from my MainActivity to MainActivity2 below is the code.
public class MainActivity extends AppCompatActivity {
String username ;
String password;
public void doLgin(View view) {
if(Build.VERSION.SDK_INT >= 10){
StrictMode.ThreadPolicy policy = StrictMode.ThreadPolicy.LAX;
StrictMode.setThreadPolicy(policy);
}
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password = ((EditText)findViewById(R.id.editTextPassword)).getText().toString();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/login.php?username=" + username + "&key=" + password);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Result", jsonarray);
String error = jsonObj.getJSONArray("Result").getJSONObject(0).toString();
String errormsg = "{\"Error\":\"Problem with authentication,Please login.\"}";
if (error.equalsIgnoreCase(errormsg)) {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("Username",username);
intent.putExtra("Password",password);
startActivity(intent);
}
}
And In my MainActivity2 class i created an object for MainActivity but it returns null values
.
You should store it on a static global class, say
public static class Credentials{
public static String USERNAME = "myUsername";
public static String PASSWORD = "myPassword";
}
Then you can access it anywhere on your project using:
Credentials.USERNAME = "setyourusername";
Credntials.PASSWORD = "setYourPassword;
But I wouldn't recommend this kind of implementation because it is really not secure, but as for an answer for your question, this probably is the approach you'll need.
Edit:
If the information should only be shared between that two activities, then #Faysal Ahmed 's answer is the way to go.
After this line on your first activity:
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password =((EditText)findViewById(R.id.editTextPassword)).getText().toString();
you can assign it directly to the static credentials class:
Credentials.USERNAME = username;
Credntials.PASSWORD = password;
then you can access it on your second activity the same way by calling Credentials.USERNAME and Credentials.PASSWORD
If you want to get the value from MainActivity then need to pass both values using putExtra.
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("username",username);
i.putExtra("password",password);
startActivity(i);
And from Main2Activity class you can get the value like this. Use this lines under onCreate method.
String user = getIntent.getStringExtra("username");
String pass = getIntent.getStringExtra("password");
No need to use MainActivity m = new MainActivity(); this line.
UPDATE:
public class Main2Activity extends AppCompatActivity {
String user;
String pass;
String JSON_URL = "http://182.18.163.39/m/list.php?username=admin&key=admin";
ListView listView;
java.util.List<List> tktList;
String link;
Button logoutbt;
Button ubt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Get value from intent that passed from previous Activity
user = getIntent.getStringExtra("username");
pass = getIntent.getStringExtra("password");
// Now you can use this two variable in any place.
logoutbt = (Button)findViewById(R.id.lbt);
logoutbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences SM = getSharedPreferences("userrecord", 0);
SharedPreferences.Editor edit = SM.edit();
edit.putBoolean("username", false);
edit.commit();
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
//initializing listview and hero list
listView = (ListView) findViewById(R.id.listView);
tktList = new ArrayList<>();
//this method will fetch and parse the data
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("Sno");
String Tktid = jsonobject.getString("TKTID");
link = jsonobject.getString("Link");
List list = new List(jsonobject.getString("Sno"), jsonobject.getString("TKTID"),jsonobject.getString("Link"));
tktList.add(list);
Log.i("website content", name);
Log.i("website content", Tktid);
Log.i("website content", link);
}
//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(tktList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
com.android.volley.RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
You can do something like this:
1) First, create a POJO class like this:
public class Info {
static Info info;
private String userName;
private String password;
public static Info getInstance() {
if (info == null) {
info = new Info();
}
return info;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName= userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password= password;
}
}
2) and then set your username and password like this:
Info.getInstance.setUserName("username");
Info.getInstance.setPassword("password");
3) and then get it like this in your other activities:
Info.getInstance.getUserName();
Info.getInstance.getPassword();
You can also pass your values to a intent and get those values in other activity.
Using the Intent you can pass the credentials through like this:
Intent i = new Intent(this, ActivityYouArePassingInformationTo.class);
i.putExtra("username", userNameValue);
i.putExtra("password", passwordValue);
Then in the activity that you want to receive the information you can get it through this way:
String userNameVal = intent.getStringExtra("username");
String passwordVal = intent.getStringExtra("password");
Now the variables in the MainActivity will have the username and password stored in a variable. Hope this helps :)
If username and password are only used in second activity only then you can pass these values in Intent.
In MainActivity
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("user_name", userName);
i.putExtra("password", password);
startActivity(i);
in Main2Activity onCreate() after setContentView() you can read data like this
Intent i = getIntent();
user = i.getStringExtra("user_name");
pass = i.getStringExtra("password");
Other ways are to save username and password in SharedPreferences in MainActivity and read Main2Activity. This might be useful when you want to auto fill previous username and password on next app launch.
There are many ways to solve this problem.
You can use below code in MainActivity class.
Intent i = new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("UserName",username);
i.putExtra("Password",password);
startActivity(i);
And in Main2Activity, you will get by using below code,
Intent i = getIntent();
String userName = i.getString("UserName");
String password = i.getString("Password");
Use below snippet code in MainActivity after you will get userName and
passsword.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("UserName", username);
editor.putString("Password", password);
editor.commit();
And after this, you will get these values in Main2Activity by below code.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
String userName = pref.getString("UserName", null);
String password = pref.getString("Password", null);
You can use static UserName and Password and get static value in other
Activity. like,
In MainActivity
public static String userName, password;
and set value after getting userName and password
userName = "abc"
password = "***"
Now In Main2Activity you will get these values directly by class name
String userName = MainActivity.userName;
String password = MainActivity.password;
You can use setter and getter method. In MainActivity, When you will find the
values you have to set userName and password.
Now, In Main2Activity you will get those values(UserName and Password) by
getter methods

Nothing Being Passed via $_Post to Php from login code?

I've been working on a log-in/register for an android app and have the register up and running but the log-in doesnt seem to be passing anything over to the php script via post like the register was? , I'm pretty sure the php script is fully functional as I've tested it with Postman, If anyone could point me in the right direction it would be much appreciated, Cheers
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="http://192.168.0.17/WebD/HASSAPP/login.php";
private Map<String, String> params;
public LoginRequest(String username,String password , Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
}
#Override
public Map<String,String> getParams() {
return params;
}
}
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//Edit to change title text
setSupportActionBar(toolbar);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String businessname = jsonResponse.getString("businessname");
String username = jsonResponse.getString("username");
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("businessname", businessname);
intent.putExtra("username", username);
Login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginrequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(loginrequest);
}
});
}
I cannot understand how me sending via Post on my register is working fine but On Log-in it's non responsive , Log-in button does nothing , not even send me to mainactivity like the intent's purpose,
Kind Regards,
Andrew
This overriden method should be protected. You have it as public.
#Override
protected Map<String,String> getParams() {
return params;
}
Also, for debugging purposes, you might want to override the error listener as well.

How to get Hashmap value and pass it to ResponseListener of volley

How do I pass my Hashmap properly to my responseListener? Im sorry I am new in android please guide me. I have a session manager where it stores data of user so that the user may not need to login again but I am having a hard time retrieving it and having it applied in my Volley response Listener. I want to retrieve the user_id for the reason that I need it as a WHERE in my php file. I think this is simple I just dont know how to apply or convert the hashmap value. Please help me Thanks
here is my code:
The main Activity
public class SendToDatabase extends AppCompatActivity {
RatingBar ratingBar;
TextView txtRatingValue;
SessionManager session;
//Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_to_database);
//HERE IS THE SESSIONMANAGER CODE
session = new SessionManager(getApplicationContext());
HashMap<String, Integer> user_int = session.getUserLexileNID();
final Integer user_id = user_int.get(SessionManager.KEY_USER_ID);
final EditText etComment = (EditText) findViewById(R.id.etComment);
final Button bSubmit = (Button) findViewById(R.id.bSubmit);
final RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
addListenerOnRatingBar();
// addListenerOnButton();
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String comment = etComment.getText().toString();
// final int rate = ratingBar.getNumStars();
final String rate = txtRatingValue.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Toast.makeText(SendToDatabase.this,"success"+comment,Toast.LENGTH_SHORT).show();
//Intent intent = new Intent (SendToDatabase.this, CommentArea.class);
// SendToDatabase.this.startActivity(intent);
} else {
// Toast.makeText(SendToDatabase.this,"something went wrong try again later", Toast.LENGTH_SHORT).show();
// Toast.makeText(SendToDatabase.this, "There might be some problem in the server side, please try again later", Toast.LENGTH_SHORT).show();
// Toast.makeText(SendToDatabase.this, response.toString(), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
//HERE IS WHERE I NEED TO PASS MY USER_ID
CommentRateRequest commentRateRequest = new CommentRateRequest(comment, rate, user_id, responseListener);
RequestQueue queue = Volley.newRequestQueue(SendToDatabase.this);
queue.add(commentRateRequest);
}
});
}
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
txtRatingValue = (TextView) findViewById(R.id.tvRatingValue);
// if rating value is changed,
//display the current rating value in the result (textview) automatically
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
txtRatingValue.setText(String.valueOf(rating));
}
});
}}
The CommentRateRequest others calls this as their singleton class
public CommentRateRequest (String comment, String rate,int user_id Response.Listener<String>listener){
super(Method.POST, CommentRateUrl, listener, null);
params = new HashMap<>();
params.put("comment", comment);
params.put("rate", rate);
params.put("user_id", user_id+"");
// params.put("book_id", book_id+"");
}
Codes from my SessionManager:
public void createLoginSession(String Fname, String Lname, Integer user_id, Integer lexile, String role_name, String grade_name, String password){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_FNAME, Fname);
editor.putString(KEY_LNAME, Lname);
editor.putInt(KEY_USER_ID, user_id);
editor.putInt(KEY_LEXILE, lexile);
editor.putString(KEY_ROLE_NAME, role_name);
editor.putString(KEY_GRADE_NAME, grade_name);
editor.putString(KEY_PASSWORD, password);
editor.commit();
}
//Part of the tutorial dont seem to have any problem
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_FNAME, pref.getString(KEY_FNAME, null));
user.put(KEY_LNAME, pref.getString(KEY_LNAME, null));
user.put(KEY_ROLE_NAME, pref.getString(KEY_ROLE_NAME, null));
user.put(KEY_GRADE_NAME, pref.getString(KEY_GRADE_NAME, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
return user;
}
dont pay attention to this as I just forgot to add "," thanks. ..

Categories

Resources