i am trying to get session stored variable in to a class. please see my actual code for class
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String ImageUrlName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
public String getImageUrlName() {
return ImageUrlName;
}
public void setImageUrlNamee(String Imageurlname) {
this.ImageUrlName = Imageurlname;
}
}
now i stored a value in session and i want to use in above code. Imageurlname is a url fetching from database. i want to add extra to the url. for example
this is my URl Getting form database http://example.com?id=
i stored user id in session so combining both url should be http://example.com?id=5
please see my modified code
public class GetDataAdapter extends AppCompatActivity {
public String ImageServerUrl;
public String ImageTitleName;
public String ImageUrlName;
private Session session;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new Session(GetDataAdapter.this);
HashMap<String, String> user = session.getUserDetails();
final String Uid = user.get(session.KEY_UID);
}
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
public String getImageUrlName() {
return ImageUrlName;
}
public void setImageUrlNamee(String Imageurlname) {
this.ImageUrlName = Imageurlname + Uid;
}
}
Uid is getting error. i hope you understand.
Looks like the problem is with persisting the userid in your case it is because of this.
Using instance variable to store user id which you can get only if you are getting the same object
Here are the solution(s):
Solution 1:
Using Static Variables
public class Example {
//this is the default value which will there stored before we are setting our actual userId
public static String USER_ID="DefaultId";
}
You can set and access the values this way.
Log.d("Default Value",Example.USER_ID);
//setting user id here
Example.USER_ID = "Manikanta Garikipati";
Log.d("Updated value",Example.USER_ID);
Solution 2: Using Shared preferences.
As you already know about this i would explain anyway.
Comment below if your problem is still not solved.
Here is the brief summary of the problem
The problem is not in shared preferences neither any storage.
Instead of creating a bean alone and setting the values to it , bean is extended with Activity etc.. which made things haywire..
Those who want the complete solution can go through the conversation in question.
Application class is there for you. use it and save your application level data, like this:
public class WhatEverApp extends Application
{
String mApplicationLevelVar = "Hello";
}
WhatEverApp will be the name of your app used in manifest.xml
Look here for detailed discussion on Application class.
Related
I have below database structure in firebase. I am trying to get the key value "Std IX" inside onBindViewHolder and set it in class_key. I am able to get the key value "science" using below code in post_key field but, not able to get it's child key "Std IX" in class_key using String class_key = getRef(position).child(post_key).getKey();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child(user_id).child("List_of_subjects");
FirebaseRecyclerOptions<Subject_list_GetSet> options =
new FirebaseRecyclerOptions.Builder<Subject_list_GetSet>()
.setQuery(query, Subject_list_GetSet.class)
.build();
adapter = new FirebaseRecyclerAdapter<Subject_list_GetSet, Subject_list_viewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final Subject_list_viewHolder holder, int position, #NonNull Subject_list_GetSet model) {
final String post_key = getRef(position).getKey();
String class_key = getRef(position).child(post_key).getKey();
holder.setSubject_name(post_key);
holder.setClass(class_key);
holder.setBk1(model.getBk1());
holder.setBk2(model.getBk2());
holder.setBk3(model.getBk3());
Subject_list_GetSet.java
public class Subject_list_GetSet {
private String Subject_name,Recom_bk,bk1,bk2,bk3;
public Subject_list_GetSet(){}
public Subject_list_GetSet(String Subject_name,String bk1,String bk2,String bk3){
this.Subject_name=Subject_name;
this.bk1=bk1;
this.bk2=bk2;
this.bk3=bk3;
}
public String getSubject_name() {
return Subject_name;
}
public void setSubject_name(String Subject_name) {
this.Subject_name = Subject_name;
}
public String getBk1() {
return bk1;
}
public void setBk1(String bk1) {
this.bk1 = bk1;
}
public String getBk2() {
return bk2;
}
public void setBk2(String bk2) {
this.bk2 = bk2;
}
public String getBk3() {
return bk3;
}
public void setBk3(String bk3) {
this.bk3 = bk3;
}
}
Since you create an adapter on List_of_subjects, the adapter will try to show the direct child nodes under that level in the JSON. So from the screenshot, Firebase will try to create a Subject_list_GetSet for the science node, mapping the properties directly under that in the JSON to those in your Java class.
To match the JSON structure you'd need a field/property like this in the class:
#PropertyName("Std IX")
public String stdIX;
Since I expect that this key may be dynamically generated, this may not be possible. In that case the only way to get the right data in your adapter is to use a custom SnapshotParser as shown in the documentation.
The data is not going to the Database. I need to send snake name and scientific name to the cloud. I am using android studio and there is no compilation error in this code, but real time database is not updated.
This my code:-
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText Snakename;
Button upload;
Spinner SciName;
DatabaseReference databaseSnake;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Snakename=(EditText)findViewById(R.id.snakeName);
upload=(Button)findViewById(R.id.upload);
SciName=(Spinner)findViewById(R.id.scientificName);
databaseSnake= FirebaseDatabase.getInstance().getReference("snake");
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSnake();
}
});
}
private void addSnake(){
String snakename=Snakename.getText().toString().trim();
String SCINAME=SciName.getSelectedItem().toString();
if(!TextUtils.isEmpty(snakename)){
String id=databaseSnake.push().getKey();
Snake snake=new Snake(id,snakename,SCINAME);
databaseSnake.child(id).setValue(snake);
Toast.makeText(this,"Snake Added",Toast.LENGTH_LONG).show();;
}
else{
Toast.makeText(this,"You Should enter a name",Toast.LENGTH_LONG).show();
}
}
}
and my snake class:-
public class Snake {
String snakeID;
String snakeName;
String scientificName;
public Snake()
{
}
public Snake(String snakeID, String snakeName, String scientificName) {
this.snakeID = snakeID;
this.snakeName = snakeName;
this.scientificName = scientificName;
}
public String getSnakeID() {
return snakeID;
}
public String getSnakeName() {
return snakeName;
}
public String getScientificName() {
return scientificName;
}
}
How to check whether data is saved or not in database at runtime ??
try this,
if(!TextUtils.isEmpty(snakename)){
String id=databaseSnake.push().getKey();
Snake snake=new Snake(id,snakename,SCINAME);
Map userInfo = new HashMap();
userInfo.put(id, snake);
databaseSnake.updateChildren(userInfo);
Toast.makeText(this,"Snake Added",Toast.LENGTH_LONG).show();;
}
Hope it's help full.
as the offical documentation says :
If you'd like to know when your data has been committed, you can add a completion listener. Both setValue() and updateChildren() take an optional completion listener that is called when the write has been committed to the database. If the call was unsuccessful for some reason, the listener will be passed an error object indicating why the failure occurred:
databaseSnake.child(id).setValue(snake, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError != null) {
Toast.makeText(this,"Data could not be saved. " +
firebaseError.getMessage(),Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,""Data saved successfully.",Toast.LENGTH_LONG).show();
}
}
});
I am busy adding a signup feature to my app and I have 4 activities which I use to collect the user's information. The activities are supposed to collect the details input by the user and send them all to the final activity where they will be sent to the database.
The first activity asks users to choose whether they want to use their email or phone number to sign up.
The second activity asks users to choose their username and password.
The third activity asks the user to add more personal details as well as to add a profile picture to their account.
The final activity asks the users to input their geographic details and then sends all the information sent from the other activities to the database.
The problem I am facing is that if i use Intents, i need to send data from activity to activity. Which is giving me a lot of errors, how can I the information collected in each activity to the final one and then send them all in one go.
You can use Singleton design pattern which preserves single object between all activities.
For example:
public class SignUpSingleton {
private int emailOrPhone;
private String username;
private String password;
private String firstName;
private String lastName;
private String country;
private String city;
//remaining fields here
private static SignUpSingleton instance = new SignUpSingleton();
private SignUpSingleton(){}
public static SignUpSingleton getInstance(){
return instance;
}
public int getEmailOrPhone() {
return emailOrPhone;
}
public void setEmailOrPhone(int emailOrPhone) {
this.emailOrPhone = emailOrPhone;
}
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;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
In the first activity:
SignUpSingleton.getInstance().setEmailOrPhone(1); //1 or 2
In the second activity:
SignUpSingleton.getInstance().setUsername("Tom");
SignUpSingleton.getInstance().setPassword("pass");
And so on for third and forth.
In the last activity you can send all data to the database at once, e.g:
storeInDb(
SignUpSingleton.getInstance().getEmailOrPhone(),
SignUpSingleton.getInstance().getUsername(),
SignUpSingleton.getInstance().getPassword(),
SignUpSingleton.getInstance().getFirstName(),
SignUpSingleton.getInstance().getLastName(),
//remaining params here
);
Assuming you have a method called storeInDb or alike, and inside it the database code.
Please use my code i am sure to help you
i am giving demo class of three activity
is this your FirstActivity
public class FirstActivity extends Activity
{
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.main);
}
public void onResume()
{
super.onResume();
//put this code as per your requirement
// i am just giving idea
Intent i=new Intent(this,SecondActivity.class);
i.putExtra("name","Riyaz Parasara");
i.putExtra("email","riyazparasara#gmail.com");
i.putExtra("phone","+918955094537");
i.putExtra("country","india");
startActivity(i);
}
}
is this your secondActivity
public class SecondActivity extends Activity
{
private String name,email,phone,county;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.main);
//this is first activity data
//you can get firstactivity data in second activity
//and store data into varialbles
name=getIntent().getStringExtra("name");
email=getIntent().getStringExtra("email");
phone=getIntent().getStringExtra("phone");
country=getIntent().getStringExtra("country");
}
public void onResume()
{
super.onResume();
//put this code as per your requirement
// i am just giving idea
Intent i=new Intent(this,ThirdActivity.class);
//this is first activity data put in intent
i.putExtra("name",name);
i.putExtra("email",email);
i.putExtra("phone",phone);
i.putExtra("country",country);
//this is second activity data you also put on this intent
i.putExtra("sex","male");
i.putExtra("age","24");
i.putExtra("city","jaipur");
startActivity(i);
}
}
is this your FinalActivity please read code comments carefully
public class FinalActivity extends Activity
{
private String name,email,phone,county,sex,age,city;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.main);
//this is first activity data and second activity data
//you can get firstactivity and secondactivity data in Final activity
//and store data into varialbles
name=getIntent().getStringExtra("name");
email=getIntent().getStringExtra("email");
phone=getIntent().getStringExtra("phone");
country=getIntent().getStringExtra("country");
sex=getIntent().getStringExtra("sex");
age=getIntent().getStringExtra("age");
city=getIntent().getStringExtra("city");
//all data are in instance variable please use this data whenever
}
public void onResume()
{
super.onResume();
//if you need to send data another activity
//please repeat again previous steps as per your requirement
}
}
Use a POJO class User, for instance, which will have all the attributes(name, email, location to name a few) you're likely be needing to complete the Sign up process.
Pass and update this User class object in every activity. The User class needs to implement Serializable or Percelable in order to be passable through Intent though.
public class User implements Serilizable {
private String usename;
private String email;
private Location location;
// Other attributes
// Getters and Setters
}
I am creating an application in android and I want to store data of places user selected on the google map. I am currently storing all the places by adding them all in an array and then serialize them by Gson library and it works fine and coding is very simple and easy but if i use data base instead of that that then the coding will be more complex and because implantation of data base is more complex then simply string the array of places to shared preferences. below is the class whose objects are i am storing and saving in the shared preferences but if want to store them on the data base then i have to go through more complex I have to create queries for insert, delete update etc. so suggest me that should i use db or shred preference is good for saving list of places.
package com.example.googlemapstext;
import java.util.ArrayList;
import android.location.Address;
public class MyPlace {
private int id;
private String placeName;
private Address placeAddress;
private int ringerState;
private int brightnessState;
private int wifiState;
private int gpsState;
private int bluetoothState;
private int radiusValueIndex;
private ArrayList<Contact> contactArrayList;
private String message;
private double radiusValue;
private boolean notificationCheck;
public MyPlace(int id,String placeName, Address placeAddress, String radiusValue,
int ringerState, int brightnessState, int wifiState, int gpsState,
int bluetoothState, int radiusValueIndex, ArrayList<Contact> contactArrayList,
String message, boolean notificationCheck) {
this.id=id;
this.placeName = placeName;
this.placeAddress = placeAddress;
this.radiusValue = getTrimedRadiusValue(radiusValue);
this.ringerState = ringerState;
this.brightnessState = brightnessState;
this.wifiState = wifiState;
this.gpsState = gpsState;
this.bluetoothState = bluetoothState;
this.contactArrayList = contactArrayList;
this.message = message;
this.radiusValueIndex = radiusValueIndex;
this.notificationCheck = notificationCheck;
}
private double getTrimedRadiusValue(String radiusValue)
{
radiusValue=radiusValue.replace("Radius ", "");
radiusValue=radiusValue.replace(" Meters", "");
return Double.parseDouble(radiusValue);
}
public boolean getNotificationCheck() {
return notificationCheck;
}
public void setNotificationCheck(boolean notificationCheck) {
this.notificationCheck = notificationCheck;
}
public int getRadiusValueIndex() {
return radiusValueIndex;
}
public void setRadiusValueIndex(int radiusValueIndex) {
this.radiusValueIndex = radiusValueIndex;
}
public int getRingerState() {
return ringerState;
}
public void setRingerState(int ringerState) {
this.ringerState = ringerState;
}
public int getBrightnessState() {
return brightnessState;
}
public void setBrightnessState(int brightnessState) {
this.brightnessState = brightnessState;
}
public int getWifiState() {
return wifiState;
}
public void setWifiState(int wifiState) {
this.wifiState = wifiState;
}
public int getGpsState() {
return gpsState;
}
public void setGpsState(int gpsState) {
this.gpsState = gpsState;
}
public int getBluetoothState() {
return bluetoothState;
}
public void setBluetoothState(int bluetoothState) {
this.bluetoothState = bluetoothState;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public double getRadiusValue() {
return radiusValue;
}
public void setRadiusValue(String radiusValue) {
this.radiusValue = getTrimedRadiusValue(radiusValue);
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public Address getPlaceAddress() {
return placeAddress;
}
public void setPlaceAddress(Address placeAddress) {
this.placeAddress = placeAddress;
}
public ArrayList<Contact> getContactArrayList() {
return contactArrayList;
}
public void setContactArrayList(ArrayList<Contact> contactArrayList) {
this.contactArrayList = contactArrayList;
}
public int getId() {
return id`enter code here`;
}
public void setId(int id) {
this.id = id;
}
}
The main difference between SharedPreferences and DataBase is like you mentioned :
SharedPreferences works on an Key-Value pair basis. you simply provide the Key and get back the Value you stored. that's great.
DataBase creates an SQLite Tables and you need to use queries to pull them out.
I think that if you are good with the JSON mechanism that you built, then storing a string in SharedPreferences is all you need.
But when the Data get more and more complex, and you would like quick access to any part of it, I think DB would be easier than parsing and seaching a JSON string all the time.
Yes, it might make you write more code for handling the DB queries..
I think SQLite will be better for you. I only use SharePreferences for small, simple and "key - value" structured data. (and it should be like that)
You have a lot of data, so SQLite is the way to go.
Read this for more information : Pros and Cons of SQLite and Shared Preferences
I think answer depends on how many places you want to save and what do you plan to do with them but I consider DB as hte best way to go.
With a DB you will be able to create queries to get only places you want and not load all places in a list and search in it.
To simplify DB creation (and use) you can try orm for Android like OrmLite and GreenDao. I think OrmLite is easier to use than GreenDao (but second one seems to have better performance...) and you can find multiple examples there.
In my opinion, SharedPreferences should only be used for saving user preferences data.
I don't have much experience with building well-designed object oriented systems, and this time I improvised, which lead to the system not working and not giving me any errors.
Basically in my android app, I have a user profile activity that calls a class that queries the remote database using the user ID, and returns values for user avatar and user name.
Until the class was nested inside the profile activity class it was alright, but I decided to move it out of there and change some other stuff and now when I go to My profile I do not see my avatar and I do not see my user name.
Here is the GetUserData class:
public class GetUserData extends Activity {
private String currentlyLoggedInUserString;
SharedPreferences sharedPrefs;
Editor editor;
int currentlyLoggedInUser;
private JSONParser jsonParser = new JSONParser();
private Configurationz configurationz = new Configurationz();
private ToastMaker toastMaker = new ToastMaker();
private static final String TAG_SUCCESS = "success";
private static final String TAG_USER_AVATAR = "user_avatar";
private static final String TAG_USER_NAME = "user_name";
private static final String TAG_USER_EMAIL = "user_email";
private static final String TAG_USER_SEX = "user_sex";
private static final String TAG_USER_DATE_REGISTERED = "user_date_registered";
private static final String TAG_USER_LAST_SEEN = "user_last_seen";
private static final String TAG_USER_PASSWORD = "user_password";
private static final String APP_SHARED_PREFS = "asdasd_preferences";
private String userName;
private String userEmail;
private String userSex;
private String userPassword;
private String userAvatar;
private String userDateRegistered;
private String userLastSeen;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserAvatar() {
return userAvatar;
}
public void setUserAvatar(String userAvatar) {
this.userAvatar = userAvatar;
}
public String getUserDateRegistered() {
return userDateRegistered;
}
public void setUserDateRegistered(String userDateRegistered) {
this.userDateRegistered = userDateRegistered;
}
public String getUserLastSeen() {
return userLastSeen;
}
public void setUserLastSeen(String userLastSeen) {
this.userLastSeen = userLastSeen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getApplicationContext().getSharedPreferences(APP_SHARED_PREFS, Context.MODE_PRIVATE);
new GetUserDataGetter().execute();
}
public class GetUserDataGetter extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
int success;
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// fix these shitty variables.
currentlyLoggedInUser = sharedPrefs.getInt("currentLoggedInUserId", 0);
currentlyLoggedInUserString = Integer.toString(currentlyLoggedInUser);
parameters.add(new BasicNameValuePair("user_id", currentlyLoggedInUserString));
final JSONObject json = jsonParser.makeHttpRequest(configurationz.URL_PHP_GET_USER_DATA, "POST", parameters);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// user data found
setUserLastSeen(json.getString(TAG_USER_LAST_SEEN));
setUserDateRegistered(json.getString(TAG_USER_DATE_REGISTERED));
setUserAvatar(json.getString(TAG_USER_AVATAR));
setUserSex(json.getString(TAG_USER_SEX));
setUserPassword(json.getString(TAG_USER_PASSWORD));
setUserEmail(json.getString(TAG_USER_EMAIL));
setUserName(json.getString(TAG_USER_NAME));
//return json.getString(TAG_USER_AVATAR);
return null;
} else if (success == 2) {
//toast about not being able to connect to db;
runOnUiThread(new Runnable() {
public void run() {
//this might cause some SHIT!!!!!!!!!!!! TEST IT!!!
toastMaker.toast(getBaseContext(), configurationz.ERROR_MESSAGES_SIGNUP_DEVICE_UNABLE_TO_TAKE_PHOTOS, configurationz, Toast.LENGTH_LONG);
}
});
setUserLastSeen("");
setUserDateRegistered("");
setUserAvatar("");
setUserSex("");
setUserPassword("");
setUserEmail("");
setUserName("");
return null;
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
and here is the MyProfile class:
public class MyProfile extends ActionBarAndSlidingMenu {
private TableRow myProfileActionButtonsHolder;
private TextView tvUserName;
private ImageButton iUserAvatar;
private Bitmap iUserAvatarBitmap;
private String avatarPath;
private String userName;
private static final String APP_SHARED_PREFS = "asdasd_preferences";
SharedPreferences sharedPrefs;
Editor editor;
int currentlyLoggedInUser;
boolean userLoggedInState = false;
private GetUserData getUserData = new GetUserData();
public MyProfile() {
super(R.string.app_name);
}
// do a check here whether this is the user themselves or some other user
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getApplicationContext().getSharedPreferences(APP_SHARED_PREFS, Context.MODE_PRIVATE);
setContentView(R.layout.user_profile);
// check whether user is logged in, otherwise redirect them to
// login/signup page
userLoggedInState = sharedPrefs.getBoolean("userLoggedInState", false);
if (!userLoggedInState) {
// start intent to get them out of here.
// Research whether this step is necessary at all
}
// define the view components
myProfileActionButtonsHolder = (TableRow) findViewById(R.id.userProfileActionButtonsHolder);
// set avatar image
iUserAvatar = (ImageButton) findViewById(R.id.iUserAvatar);
avatarPath = getUserData.getUserAvatar();
if (avatarPath != "") {
iUserAvatarBitmap = BitmapFactory.decodeFile(avatarPath);
iUserAvatar.setImageBitmap(iUserAvatarBitmap);
} else {
iUserAvatar.setImageResource(R.drawable.avatar_default_male);
}
//set user display name
userName = getUserData.getUserName();
tvUserName = (TextView) findViewById(R.id.tvUserName);
tvUserName.setText(userName);
// create action buttons fragment with "edit" and "settings" buttons
getSupportFragmentManager().beginTransaction().replace(R.id.userProfileActionButtonsHolder, new MyProfileActionButtonsFragment()).commit();
}
}
First, you need to read up on programming in general and proper coding guidelines in particular, as this is a bit of a chaos. As soon as your project becomes more complex, this gets unreadable and undebuggable. Second, you should read up on how Android works.
Here's your problem in a nutshell:
An Activity is not just Android's own version of a class and you can't use it as such. An Activity represents a screen that is displayed to the user. No screen to display? No Activity.
Thus, your getUserData Activity should be a regular class and not extend activity.
Now, in MyProfile you just declare a member variable with
private GetUserData getUserData = new GetUserData();
This does nothing and it certainly never runs that class' onCreate. Thus, your task is never executed and all your fields return null.
Here's what to do in a nutshell:
Create a class UserDetails that has a constructor that takes the username, etc. plus the getters necessary to get these details. Add nothing else. This is what we call Java's version of a value object.
public class UserDetails {
private final String mUsername;
public UserDetails(String username) {
mUsername = username;
}
public String getUsername() {
return mUsername;
}
}
Create an interface called IOnUserDetailsReceivedListener with the method onUserDetailsReceived(UserDetails userDetails). The reason for this is that your download task will take some time. You need to get informed when it's done and that's what we use this interface for. This is called a listener pattern.
public interface IOnUserDetailsReceivedListener {
public void onUserDetailsReceived(UserDetails userDetails);
public void onUserDetailsError();
}
Create a class Downloader that contains your AsyncTask and that has a method retrieveUserDetails(); or something. In that method, run the async task to download. When you get the data from the server, fill it into a new UserDetails(...) object and then call listener.onUserDetailsReceived(userDetails).
public class UserDetailsDownloader {
private IOnUserDetailsReceivedListener mListener;
public UserDetailsDownloader(IOnUserDetailsReceivedListener listener) {
mListener = listener;
}
public void downloadUserDetails() {
//Execute the async task here. In it's onPostExecute, do mListener.onUserDetailsReceived(userDetails).
}
private class DownloaderTask extends AsyncTask<String, Integer, UserDetails> {
#Override
protected UserDetails doInBackground(String... params) {
//Download code
//In downloading there might go stuff wrong. If so, return null as an easy method without any error handling.
UserDetails userDetails = new UserDetails("downloadedUsername");
return userDetails;
}
#Override
protected void onPostExecute(UserDetails userDetails) {
if(userDetails == null) {
if(mListener != null) {
//Something went wrong. Tell the listener.
mListener.onUserDetailsError();
}
} else {
if(mListener != null) {
//Cool! Lets pass the userDetails to the activity.
mListener.onUserDetailsReceiver(userDetails);
}
}
}
}
}
Let your activity implements IOnUserDetailsReceivedListener.
public void UserActivity extends Activity implements IOnUserDetailsReceivedListener {
private UserDetailsDownloader mUserDetailsDownloader;
public void onCreate(...) {
mUserDetailsDownloader = new UserDetailsDownloader(this);
mUserDetailsDownloader.downloadUserDetails();
}
public void onUserDetailsReceived(UserDetails userDetails) {
//Yeeh we received user data.
}
public void onUserDetailsError() {
//Something went wrong. Tell the user?
}
}
When your task is done, it'll call your Activities onUserDetailsReceived method and pass you the UserDetails value object with which you can then do what you want.
I don't know if this is your only problem or not but too much for a comment. You shouldn't use runOnUiThread() in doInBackground()
runOnUiThread(new Runnable() {
public void run() {
//this might cause some SHIT!!!!!!!!!!!! TEST IT!!!
toastMaker.toast(getBaseContext(), configurationz.ERROR_MESSAGES_SIGNUP_DEVICE_UNABLE_TO_TAKE_PHOTOS, configurationz, Toast.LENGTH_LONG);
}
});
this is why AsyncTask has onPostExecute() and its other methods...they all run on the UI Thread except for doInBackground()
Instead of return null, returnsuccessand depending on that value, do what you need to inonPostExecute()`.
Edit
onPostExecute() gets its parameter from what doInBackground() returns which is the third param in your declaration public class GetUserDataGetter extends AsyncTask<String, String, String>. So you can change that param or return a String to onPostExecute() from doInBackground().
AsyncTask Docs