I am currently building a login system for a simple game application. What I am trying to achieve is the following: When a user logs in I want to display the top 5 highscores in the activity the user comes to after logging in.
The response I am getting from the database is a JSON encoded string looking like this:
{"success":true,"toplist":
[{"username":"Tom","score":"4200"},
{"username":"John","score":"2303"},
{"username":"Benjamin","score":"700"},
{"username":"Michael","score":"648"},
{"username":"Daniel","score":"500"}]
}
From here I would like to "handle" and pass the top 5 information to the userAreaActivity and then show the top 5 in a table.
Here is what I have so far in order to handle the response:
bSignIn.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){
Intent userAreaIntent = new Intent(LoginActivity.this, UserAreaActivity.class);
LoginActivity.this.startActivity(userAreaIntent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.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(LoginActivity.this);
queue.add(loginRequest);
}
});
If it is of any use this is what my UserAreaActivity.Java looks like:
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TableLayout tlHighscores = (TableLayout) findViewById(R.id.tlHighscores);
Intent intent = getIntent();
}
}
Would be thrilled if someone would give me some guidance as to how I would do this in the most convenient way.
You can simply do this
Intent userAreaIntent = new Intent(LoginActivity.this, UserAreaActivity.class);
userAreaIntent.putString("data", jsonResponse.toString());
LoginActivity.this.startActivity(userAreaIntent);
And in UserAreaActivity
JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("data"));
Once you get the jsonObj you can parse it and use it anyway you want.
This is what the Intent object is for - to provide an intent along with associated information. You can simply do:
Intent intent = new Intent(this, UserAreaActivity.class);
intent.putString("key", "value");
startActivity(intent);
Now, you can do intent.getStringExtra("key") in your receiving Acitivity to extract the values. You can pass your entire JSON string and retrieve information this way.
Related
I want to make an app that the user enter information and it upload it to a google sheet file. I have a google app script which works (I runed it with values) and a code in Java for the app which don't work.. I will be very please if someone can help me understand what I do wrong
Thanks, Ido
Google app script
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1jCxPiqvHOwVJrWdzY_Ccy49i-rtOD8AeFrf53KwN3OQ/edit#gid=0")
var sheet = ss.getSheetByName('Users');
function doPost(e){
var action = e.parameter.action;
if(action == 'addUser'){
return addItem(e);
}
}
function addItem(e){
var name = e.paramete.vName;
var phone = e.parameter.vPhone;
var area = e.parameter.vArea;
sheet.appendRow([name, phone, area]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
}
Java Code
public void addUserData(){
String name = fullName.toString();
String phone = phoneNumber.toString();
String area = place;
StringRequest stringRequest = new StringRequest(Request.Method.POST, "URL", new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Intent intent = new Intent(getApplicationContext(), CorrectActivity.class);
startActivity(intent);
progressDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Intent intent = new Intent(getApplicationContext(), FailedActivity.class);
startActivity(intent);
progressDialog.hide();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("action", "addUser");
params.put("vName", name);
params.put("vPhone", phone);
params.put("vArea", area);
return params;
}
};
int socketTimeOut = 50000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut,0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I am trying to save my data to server. can any one help me?
when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??
public class Register extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
etCity;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.name);
etEmail = (EditText) findViewById(R.id.email);
etMobile = (EditText) findViewById(R.id.mobile);
etCity = (EditText) findViewById(R.id.etCity);
etPassword = (EditText) findViewById(R.id.password);
//etRePassword = (EditText) findViewById(R.id.rePassword);
register = (Button) findViewById(R.id.bRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String email = etEmail.getText().toString();
final String password = etPassword.getText().toString();
final String city = etCity.getText().toString();
final String phoneno = etMobile.getText().toString();
StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + " Response");
if(response.equals("SUCCESS")){
startActivity(new Intent(Register.this,MainActivity.class));
}
else{
Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.toString());
if(error.networkResponse == null){
if(error.getClass().equals(TimeoutError.class));
Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders()throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("name",name);
headers.put("email",email);
headers.put("password",password);
headers.put("city",city);
headers.put("phoneno",phoneno);
return headers;
}
};
registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + "");
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Registration failed").setNegativeButton("Retry", null)
.create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//super.getHeaders();
Map<String,String> headers = new HashMap<>();
String credential = "raju#gmail.com:123";
String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
//headers.put("Content-Type");
headers.put("Authorization",auth);
//
return headers;
}
};*/
RequestQueue queue = Volley.newRequestQueue(Register.this);
registerRequest.setShouldCache(false);
queue.add(registerRequest);
}
}
Here Is my server code....
#RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public #ResponseBody String saveUser(#RequestBody MobileUserModel mobileUser) {
MobileUserModel user = new MobileUserModel();
user.setActivationKey(mobileUser.getActivationKey());
user.setCity(mobileUser.getCity());
user.setEmail(mobileUser.getEmail());
user.setImeino(mobileUser.getImeino());
user.setName(mobileUser.getName());
user.setPassword(mobileUser.getPassword());
user.setPhoneno(mobileUser.getPhoneno());
userrepository.save(user);
System.out.println("Saved");
// return "User has been saved Successfully";
return "SUCCESS";
}
Put following inside your onClick method:
switch (v.getId()) {
case R.id.bRegister:
// add your registration process code here
break;
}
Make Sure you have given Internet permissions in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Please provide your json response format and also the parameter type that you are sending. It may occur due to different reasons, for example, there is an json array in response and you are mapping it just in simple object or the attributes (variable) that you are mapping into it, names are not exactly similar to json response filed or there can be different multiple reasons.
The problem is definitely from this code.
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etuserame.getText().toString();
final String email = etemail.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) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
when the user clicks register, it does not open the new activity and I get nothing in my database. I just get a cancelling event due to no window focus and too many processes running.
This is my RegisterRequest class.
private Map<String, String> params;
public RegisterRequest(String username, String email, String password, Response.Listener<String> listener){
/*
NExt line means we are going to pass some information into the register.php
*/
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
/*
This is how we pass in the information from the register to the thing, we are using a hashmap
*/
params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
}
/*
Volley needs to get the data so we do a get params
Which gives us this method
*/
#Override
public Map<String, String> getParams() {
return params;
}
}
Below is my working login code. I now want the 'name' the person logged in with to be displayed on a profile page. Searched all over but could not find it.
For example:
Person logged in with name 'example#mail.com' ('username' in code below). I want 'example#mail.com' to be displayed on a TextView on a different page.
Thanks for the help!
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://calisapp.esy.es/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
editTextUserName.requestFocus();
editTextUserName.setError("Wrong E-mail address or password");
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
There are three ways, you can do this
1. Using Shared Preferences
2. Storing the value on Local Database
3. Passing the value via Intent.
If their login is successful, use SharedPreferences to store it. Something like this:
SharedPreferences myPrefs = getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
myPrefs.edit().putString(EMAIL_KEY, someEmail#example.com).apply();
myPrefs.edit().putString(PASSWORD_KEY, somePassword).apply();
EDIT: DOES NOT WORK FOR SOME REASON.
Thanks guys. I did not know you could use multiple intents so I did that. If anyone happens to need to know how I did it. Probably better to use shared preferences but I just need it on one more page for now, and I'm not a fan of making things harder than they could be.
I added a second intent to the login class on successfull login, that will carry the username string over to my settings/profile.
Intent intent2 = new Intent (MainActivity.this, Settings.class);
intent2.putExtra(USER_NAME, username);
On the settings page I called it by a intent.getStringExtra. I used a textview to show the string.
Intent intent2 = getIntent();
String username = intent2.getStringExtra(MainActivity.USER_NAME);
TextView showEmail = (TextView) findViewById(R.id.SettingsShowEmail);
showEmail.setText(username);
Intent intent2 = new Intent (MainActivity.this, Settings.class);
intent2.putExtra("username", username);
startActivity(intent2);
on the settings activity
String username = getIntent().getExtras().getString("username");
TextView showEmail = (TextView) findViewById(R.id.SettingsShowEmail);
showEmail.setText(username);
this is the LoginActivty
public class MainActivity extends Activity {
ProgressDialog prgDialog;
TextView errorMsg;
EditText emailET;
EditText pwdET;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
errorMsg = (TextView) findViewById(R.id.login_error);
emailET = (EditText) findViewById(R.id.loginEmail);
pwdET = (EditText) findViewById(R.id.loginPassword);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btnLogin);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
// call the async task
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
}
then I am using a AsyncTask, this the code
public class HttpAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private static InputStream stream = null;
private static String API;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public HttpAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.x.xxx/xxxxService/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Log.i("Login Success", "Success message");
} else {
Log.e("Login Error", "Error converting result ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
when I enter correct email and password, it comes to this line
Log.i("Login Success", "Success message");
from there I want to open the HomeActivty but it doesn't allow me to use intent, or even to toast
I need help to implement directing to Home Activity once the logging is success.
Here:
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Because you are getting result on Main Thread by calling AsyncTask.get() method AsyncTask.
First just call AsyncTask.execute method to start AsyncTask task :
new HttpAsyncTask(MainActivity.this).execute(email,password);
then use onPreExecute() to show progessbar and onPostExecute for starting next Activity :
#Override
protected void onPreExecute() {
// show ProgressDialog here
}
#Override
protected void onPostExecute(Void result) {
// parse json here and start Home Activity
//.........your code here
if (test.equals("200")) {
Log.i("Login Success", "Success message");
Intent intent = new Intent(contxt,HomeActivity.class);
contxt.startActivity(intent);
} else {
Log.e("Login Error", "Error converting result ");
}
}
You can start activity like this from AsyncTask, You should use the context.
mContext.startActivity(new Intent(CurrentActivity.this, Home.class));
Or try like this also
Intent intent = new Intent();
intent.setClass(getApplicationContext(),Home.class);
startActivity(intent);
I know there is another valid answer to fix your problem. But to precisely explain why your error exists, I give my answer below.
To create an Intent for startActivity(), this can be done by:
Intent i = new Intent(currentActivity, NextActivity.class);
startActivity(i);
Notice that the first parameter of constructor of Intent is android.content.Context, in which Activity is a subclass of it. So in any situation, you can always pass the Context to your custom class and start a new Activity or create a Toast with this Context.
In your question, private Context contxt; in HttpAsyncTask is the context your need to do everything.
Reference: http://developer.android.com/reference/android/content/Intent.html#Intent%28android.content.Context,%20java.lang.Class%3C?%3E%29