How to use a value across all activities? - android

For example: I have a String value "A". and I have activities : activity_a, activity_b, activity_C.
Can I use value "A" across all activities? If yes how to achieve this?
And not through Intent or send data to another activity.
I am sorry that I am not fluent in English.
I moved a token value in login activity to main activity.
I used Intent and move token login activity. this is my login activity code.
StringRequest stringRequest = new StringRequest(Request.Method.POST, serverURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
JSONObject json_code = jsonArray.getJSONObject(0);
JSONObject json_token = jsonArray.getJSONObject(1);
String code = json_code.getString("code");
String token = json_token.getString("token");
Intent myIntent = new Intent(loginActivity.this, mainActivity.class);
myIntent.putExtra("token", token);
startActivity(myIntent);
finish();
overridePendingTransition(R.xml.madefadein, R.xml.splashfadeout);
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
switch(error.networkResponse.statusCode)
{
case 409:
Toast.makeText(loginActivity.this, error.networkResponse.toString(), Toast.LENGTH_SHORT).show();
break;
}
}
but in main Activity, I tried to declare static like this.
Intent i = new Intent(getIntent());
public static final String token = i.getStringExtra("token");
but it doesn't work.

1.just declare your String as public static String strTmp="A"; in your activity than you can use any where in your project
like this
String strTmp = yourActivity.str;
2. create a new class like this
public class ServiceClass {
public static String strTmp="Data";
}
now you can access this string anywhere in your project like this
String mystr= ServiceClass.strTmp;
3.if you want use hard String than store your string in res/values/string.xml like this
<resources>
<string name="app_name">PatternView</string>
</resources>
than you can use like this
String str = getResources().getString(R.string.app_name);
4. save it in SharedPreferences like this
code for save data in SharedPreferences like this
SharedPreferences myPref;
SharedPreferences.Editor prefEditor;
myPref = getSharedPreferences("TOKENNAME", MODE_PRIVATE);
prefEditor = myPref.edit();
prefEditor.putString("TOKEN", "your token");
prefEditor.apply();
code for retrieve data from SharedPreferences
SharedPreferences myPref;
myPref = getSharedPreferences("TOKENNAME",
MODE_PRIVATE);
String name = myPref.getString("TOKEN", "");

Related

Onetime login is not working and second time also showing LoginActivity in android

Hi in the below code I was implemented ontime login feature but it is not working with below code.If login is successful then it will redirecting to MainActivity.Next time want to skip login page directly it should show main activity.
SplashActivity.java:
final boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
if(!needLogin) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
},
Once the login is successfull it will redirect to MAninactivity.java.Entire app I am using session.
LoginActivity.java:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
String sessionId = loginDetails.getSession();
String firstname = loginDetails.getFirst_name();
String lastname = loginDetails.getLast_name();
String mobile = loginDetails.getMobile();
String role = loginDetails.getRole();
String reportto = loginDetails.getReportto();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for (LoginListForModules module : modules) {
module_id = module.getId();
String name = module.getName();
String isEntity = module.getIsEntity();
String label = module.getLabel();
String singular = module.getSingular();
}
if (username.equals(username1.getText().toString()) && password.equals(password1.getText().toString())) {
// fetchUserJSON(sessionId,username);
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
i = new Intent(LoginActivity.this, MainActivity.class);
// loader.setVisibility(View.GONE);
progressDialog.dismiss();
// llProgressBar.setVisibility(View.GONE);
i.putExtra("sessionId", sessionId);
i.putExtra("module_id", module_id);
i.putExtra("username", username);
i.putExtra("firstname", firstname);
i.putExtra("lastname", lastname);
i.putExtra("mobile", mobile);
i.putExtra("role", role);
i.putExtra("reportto", reportto);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
}
You can use SharedPreferences.
A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them.
DEMO CODE
public class SharedPreferenceClass
{
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Test";
public static final String KEY_SET_LOGIN_STATUS= "KEY_SET_LOGIN_STATUS";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setLoginStatus(String status)
{
editor.remove(KEY_SET_LOGIN_STATUS);
editor.putString(KEY_SET_LOGIN_STATUS, status);
editor.commit();
}
public String getLoginStatus()
{
String status= pref.getString(KEY_SET_LOGIN_STATUS, "");
return status;
}
}
Now you can store login status ( setLoginStatus("Login")) when ever login success And check your login status getLoginStatus(). If return "Login" then return to your desire activity.

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

Android: Value out of JSONObject/responseListener

I try to save the userid to work with it in a different Activity, but I was not able to get the value out of the try catch statement. I should mention that I am new to Android. (Also the AlertDialog is not working but that is not important). Thanks for help!
EDIT: I just found this out: The code down below is for the "First Screen" (shown by the first start of the App) and after you click on the button you will get to the MainActivity. If I close the App after the First Screen opened MainActivity, and open it again, the SharedPreferences are working perfectly.
button = (Button) findViewById(R.id.savebtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next_page(v);
}
});
}
public void next_page(View v){
final String firstname1 = firstnameFS.getText().toString();
final String lastname1 = lastnameFS.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");
int userid = jsonResponse.getInt("userid");
if(success){
AlertDialog.Builder builder3 = new AlertDialog.Builder(FirstScreen.this);
builder3.setMessage("Updated! Id:"+userid);
builder3.create().show();
SharedPreferences mySPR = getSharedPreferences("MySpFile", MODE_PRIVATE);
SharedPreferences.Editor editor = mySPR.edit();
editor.putString("firstnameSP", firstname1);
editor.putInt("useridSP", userid);
editor.commit();
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(FirstScreen.this);
builder.setMessage("Update Failed");
builder.create().show();
}
} catch (JSONException e){
e.printStackTrace();
}
}
};
RegisterRequestFS registerRequestFS =new RegisterRequestFS(firstname1,lastname1, responseListener);
RequestQueue queue = Volley.newRequestQueue(FirstScreen.this);
queue.add(registerRequestFS);
Simply move your shared preferences edit command inside the if(success) block.
After committing the useridSP inside your shared preference retrieve it with this code:
SharedPreferences mySPR = getSharedPreferences("MySpFile", MODE_PRIVATE);
mySPR.getInt("useridSP",-1);
-1 value stays for default value, so be aware that if you get -1 for the useridSP in the new activity you're doing something wrong

Unable to access SharedPreferences value from a class into an activity

I am working on a server baser application so whenever a user logs in i have to capture his unique userId and use it in different activities in my whole project.
So after getting the userId from JSONObject i am putting it in sharedPrederence and getting it in another activity but after entering into my main activity which is after successful login the shared preference shows me the default value of userId which is zero.
Here is my code in PostData.java class which will work in background of login activity:
private SharedPreferences userIdSharedPreferences;
private SharedPreferences.Editor userIdEditor;
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply();
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
and here is how i am using that sharedPreference value in other acitivity:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("crrUserId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show(); //This toast showing 0 which is default i set.
EDIT
for more clarification now i am passing my userId from my background class PostData.java to my LoginActivity using the below function:
Integer passUserId() {
return userId;
}
and from there i am passing userId using sharedPreference like this:
Intent loginSuccess = new Intent(getApplicationContext(), MainActivity.class);
Integer crrUserId = Login.passUserId(); //Login is name of variable which will accespassUserId function in PostData.java class
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("userId", 0);
SharedPreferences.Editor userIdEditor;
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", crrUserId);
userIdEditor.apply();
startActivity(loginSuccess);
finish();
and here is how i am using in my mainactivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences userIdSharedPreferences;
SharedPreferences.Editor userIdEditor;
Integer crrUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("userId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show();
}
Try this:
First you need to initialize userIdSharedPreferences object like below:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
After getting object of SharedPreference do this:
userIdEditor = userIdSharedPreferences.edit();
After getting object of SharedPreferences.Editor do your task.
initialiase userIdSharedPreferences may be thats the problem
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply(); //apply or commit not both
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Correct way of getting a Json position

After the login I get this response from the webserver..
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
Ok. Now My android code.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This code Toast the following message. "Bem vindo lu#lu.com"
What I want is:
How can I get the other infos and pass it to a String.
Email = "lu#lu.com"
Endereco = "Rua Pedro..."
Name = "Lu Zimermann"
Soo I can use it later on the app.
Thanks.
Now the response is the right way you can do this to save data..
first wirte a custion class for Preferennce
SharedPreferenceCustom
public class SharedPreferenceCustom {
private Context mContext;
private String defValue = "";
public SharedPreferenceCustom(Context context) {
this.mContext = context;
}
public void setSharedPref(String inputKey, Object inputValue) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getString(inputKey, defValue);
}
}
Now for saving the data, in the activity
try {
JSONObject response = new JSONObject(new String(response_from_server))
SharedPreferenceCustom sp = new SharedPreferenceCustom(Activity.this);
sp.setSharedPref("key_1", response.getString("nomeusuario")); // use key as per needed
sp.setSharedPref("key_2", response.getString("enderecousuario"));
sp.setSharedPref("key_3", response.getString("telefoneusuario"));
sp.setSharedPref("key_4", response.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
And for getting the data call sp.getSharedPref("key"); pass the key for getting the corresponding data
EDIT: you can also write individual function in SharedPreferenceCustion to store different data type, or you can use just this, But it might create some conflicts for certain data types,
Hope this helps :) :)
To get access to the other keys, you can use the get(key) on the jsonObject object. Here are the code changes you need to make:
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
//here I am just getting the other properties/keys
String nomeusuario = jsonObject.getString("nomeusuario");
String enderecousuario = jsonObject.getString("enderecousuario");
String telefoneusuario = jsonObject.getString("telefoneusuario");
//here you could do whatever you like - I am just making a Toast as an example:
Toast.makeText(getApplicationContext(), nomeusuario+ ", "+enderecousuario+ ", "+telefoneusuario ,Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I hope this helps you - give it a try and let me know.
By the way, I am assuming the JSON that you are getting is proper.
There are several ways you can do that.
First of all you need to store them into variable/s.
You can choose to keep it as JSON var, as HashMap or each variable separate as String.
The second action is to access it from any place. This depends on how long to you want the information alive.
If you want them live for just as long as the app is live then the I suggest to create a Global Java class with set/get of your variable.
You could also store it in SharedPreferences or sqlite database for permanent.
Try following
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if(jsonObject.names().get(0).equals("success")){
//Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
String values = "";
while(keys.hasNext()){
String keyName = keys.next();
values = jsonObject.getString(keyName) + "\n";
}
Toast.makeText(getApplicationContext(),values,Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources