This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This is what my Firestore data structure looks like
Hello, i have an issue and i have searched online but nothing seem to come close to what am facing. i am using firestore to store my data
This is the users node.
user section
And this is the user_account_settings node.
user_account_settings section
The goal is to loop through these nodes and retrieve/get data from the node and set them into text and display them using custom models.
this is the model for Account settings
public class UserAccountSettings {
private String description;
private String display_name;
private long followers;
private long following;
private long posts;
private String profile_photo;
private String username;
private String website;
public UserAccountSettings(String description, String display_name, long followers, long following,
long posts, String profile_photo, String username, String website) {
this.description = description;
this.display_name = display_name;
this.followers = followers;
this.following = following;
this.posts = posts;
this.profile_photo = profile_photo;
this.username = username;
this.website = website;
}
public UserAccountSettings(){
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public long getFollowers() {
return followers;
}
public void setFollowers(long followers) {
this.followers = followers;
}
public long getFollowing() {
return following;
}
public void setFollowing(long following) {
this.following = following;
}
public long getPosts() {
return posts;
}
public void setPosts(long posts) {
this.posts = posts;
}
public String getProfile_photo() {
return profile_photo;
}
public void setProfile_photo(String profile_photo) {
this.profile_photo = profile_photo;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
#Override
public String toString() {
return "UserAccountSettings{" +
"description='" + description + '\'' +
", display_name='" + display_name + '\'' +
", followers=" + followers +
", following=" + following +
", posts=" + posts +
", profile_photo='" + profile_photo + '\'' +
", username='" + username + '\'' +
", website='" + website + '\'' +
'}';
}
}
and user model
public class User {
private String user_id;
private long phone_number;
private String email;
private String username;
public User(String user_id, long phone_number, String email, String username) {
this.user_id = user_id;
this.phone_number = phone_number;
this.email = email;
this.username = username;
}
public User(){
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public long getPhone_number() {
return phone_number;
}
public void setPhone_number(long phone_number) {
this.phone_number = phone_number;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "User{" +
"user_id='" + user_id + '\'' +
", phone_number='" + phone_number + '\'' +
", email='" + email + '\'' +
", username='" + username + '\'' +
'}';
}
}
User settings (Holding both user and user_account_settings)
public class UserSettings {
//for handling multilple queries in database : users and user_account_settings.
private User user;
private UserAccountSettings settings;
public UserSettings(User user, UserAccountSettings settings) {
this.user = user;
this.settings = settings;
}
public UserSettings(ArrayList<User> mUser, ArrayList<UserAccountSettings> mSettings){
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserAccountSettings getSettings() {
return settings;
}
public void setSettings(UserAccountSettings settings) {
this.settings = settings;
}
#Override
public String toString() {
return "UserSettings{" +
"user=" + user +
", settings=" + settings +
'}';
}
}
trying to retrieve and set the data from firestore to the models
public UserSettings getUserSettings(final DocumentSnapshot documentSnapshot){
Log.d(TAG, "getUserSettings: retrieving user account settings from firestore");
final ArrayList<UserAccountSettings> mSettings = new ArrayList<>();
final ArrayList<User> mUser = new ArrayList<>();
//handling user_account_settings_node.
mFirestore.collection("user_account_settings").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: FirebaseFirestoreException", e);
return;
}
for (DocumentSnapshot document : documentSnapshots) {
Log.d(TAG, document.getId() + " => " + document.getData());
if (document.getId().equals("user_account_settings")){
Log.d(TAG, "checking if id equals user_account_settings: yes, it does");
Log.d(TAG, "onSuccess: Document" + document.getId() + ";" + document.getData());
UserAccountSettings settings = document.toObject(UserAccountSettings.class);
Log.d(TAG, "UserAccountSettings: " + "username is" + settings.getUsername());
settings.setDisplay_name(documentSnapshot.getString("display_name"));
settings.setUsername(documentSnapshot.getString("username"));
settings.setWebsite(documentSnapshot.getString("website"));
settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
settings.setPosts(documentSnapshot.getLong("posts"));
settings.setFollowers(documentSnapshot.getLong("followers"));
settings.setFollowing(documentSnapshot.getLong("following"));
mSettings.add(settings);
}
}
}
});
//handling users node.
mFirestore.collection("users").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshots) {
Log.d(TAG, document.getId() + " => " + document.getData());
if (document.getId().equals(mContext.getString(R.string.dbname_users))){
Log.d(TAG, "checking if id equals user_account_settings: yes, it does");
Log.d(TAG, "onSuccess: Document" + document.getId() + ";" + document.getData());
User user = document.toObject(User.class);
Log.d(TAG, "user: got the user information" + "user I.D is "+ user.getUser_id());
user.setUsername(documentSnapshot.getString("username"));
user.setEmail(documentSnapshot.getString("email"));
user.setPhone_number(documentSnapshot.getLong("phone_number"));
user.setUser_id(documentSnapshot.getString("user_id"));
mUser.add(user);
}
}
}
});
return new UserSettings(mUser, mSettings );
}
and i try getting these data from the documents
//setting Profile Widgets
private void setProfileWidgets(UserSettings userSettings){
Log.d(TAG, "setProfileWidgets: Setting widgets with data retrieved from firebase firestore" + userSettings.toString());
Log.d(TAG, "setProfileWidgets: searching for username" + userSettings.getSettings().getUsername());
User user = userSettings.getUser();
UserAccountSettings settings = userSettings.getSettings();
try {
UniversalImageLoader.setSingleImage(settings.getProfile_photo(), mProfilePhoto, null, "");
mDisplayname.setText(settings.getDisplay_name());
mUsername.setText(settings.getUsername());
mWebsite.setText(settings.getWebsite());
mDescription.setText(settings.getDescription());
mPosts.setText(String.valueOf(settings.getPosts()));
mFollowers.setText(String.valueOf(settings.getFollowers()));
mFollowing.setText(String.valueOf(settings.getFollowing()));
mProgressBar.setVisibility(View.GONE);
}
catch (NullPointerException e){
Log.e(TAG, "setProfileWidgets: NullPointerException" + e.getMessage());
}
}
then i initialize the widgets
mFirebaseFirestore = FirebaseFirestore.getInstance();
myUserRef = mFirebaseFirestore.collection("users");
myUserSettingsRef = mFirebaseFirestore.collection("user_account_settings");
myUserSettingsRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshot) {
Log.d(TAG, document.getId() + " => " + document.getData());
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(document));
}
}
});
myUserRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshot) {
Log.d(TAG, document.getId() + " => " + document.getData());
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(document));
}
}
});
When i run the app, this is what i get
error message
if you see the code, i can see other user information. but it throws me a null pointer exception on my widgets (user=null , settings=null). i have gone through all the widgets id's and its correct am wondering if someone can point out where am getting wrong. thanks in advance
The UserSettings class has a constructor that looks like this:
public UserSettings(ArrayList<User> mUser, ArrayList<UserAccountSettings> mSettings){
}
This constructor doesn't set the user and settings variables defined in this class and it is the constructor you use to create the return value of the getUserSettings method.
return new UserSettings(mUser, mSettings ); // `mUser` and `mSettings` are `ArrayList`s
Hence the exception.
This is the main problem, the one that generates the exception you've mentioned but it is not the only problem.
Related
I have an Api, Api = "http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/admin/"
I am new to Retrofit2, If some one can help me through my code
I have an Error while doing GET and POST Request
While Using Get Api: the Username and password are null
While Using Post Api: I am getting 404 Error code
Login Activity:
private JsonPlaceHolderApi jsonPlaceHolderApi;
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
getLogin();
createPost();
}
private void getLogin()
{
Call<Login> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<Login>()
{
#Override
public void onResponse(Call<Login> call, Response<Login> response)
{
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login logins = response.body();
String content = "";
content += "UserName: " + logins.getUsername() + "\n";
content += "Password: " + logins.getPassword() + "\n";
content += "Status: " + logins.getStatus() + "\n";
content += "Description: " + logins.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<Login> call, Throwable t)
{
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
Login login = new Login("New Name", "New Password");
Call<Login> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.getUsername() + "\n";
content += "Password: " + loginResponse.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me",content);
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
Login Class:
String username;
String password;
int Status;
String Description;
public Login(String username, String password)
{
this.username = username;
this.password = password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public int getStatus()
{
return Status;
}
public String getDescription()
{
return Description;
}
And An Interface Class Called JsonPlaceHolderApi
public interface JsonPlaceHolderApi
{
#GET("admin")
Call<Login> getLogin();
#POST("admin")
Call<Login> createPost(#Body Login login);
}
Starting with the GET issue, you are getting fields (Username and password) equals to null because they are not at the top level of your JSON, so, in order to fix the GET issue you need to create the following class :
LoginResponse
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#SerializedName("Users")
User user;
#SerializedName("Status") int status;
#SerializedName("Description") String description;
}
Add a user class which will host all the user's data :
User
public class User {
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getClientno() {
return clientno;
}
public void setClientno(String clientno) {
this.clientno = clientno;
}
public String getCompanyno() {
return companyno;
}
public void setCompanyno(String companyno) {
this.companyno = companyno;
}
public String getUserno() {
return userno;
}
public void setUserno(String userno) {
this.userno = userno;
}
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 int getRowno() {
return rowno;
}
public void setRowno(int rowno) {
this.rowno = rowno;
}
String clientno;
String companyno;
String userno;
String username;
String password;
int rowno;
}
Then update your JsonPlaceHolderApi interface to return a Call<LoginResponse> instead of Call<Login> :
#GET("admin")
Call<LoginResponse> getLogin();
#POST("admin")
Call<LoginResponse> createPost(#Body User login);
One more thing, replace both getLogin() and createPost() with the following :
private void getLogin() {
Call<LoginResponse> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
User login = new User("New Name", "New Password");
Call<LoginResponse> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
For the POST issue, 405 (Method Not Allowed), it seems like the "admin" action doesn't support the POST method.
i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
I have some issues with Retrofit2 while posting data to an API using POST request.
The response from the server is successful but all the values displayed on the response are null :
I/SUCCESS: test : Post{id='null', titre='null', description='null', prix='null', pseudo='null', emailContact='null', telContact='null', ville='null', cp='null', image='null', date='null'}
Here is an example of the JSON that I've to receive
{
"success": true,
"response": {
"id": “5a5f11196c2aa”,
"titre": "Vends 406",
"description": "Pas chere",
"prix": "4500",
"pseudo": "jml",
"emailContact": "",
"telContact": "Vends 406",
"ville": "",
"cp": "",
"images": [],
"date": 1516179737
}
}
Here is my data model :
public class Post {
#SerializedName("cp")
private String cp;
#SerializedName("date")
private Long date;
#SerializedName("description")
private String description;
#SerializedName("emailContact")
private String emailContact;
#SerializedName("id")
private String id;
#SerializedName("images")
private String[] images;
#SerializedName("prix")
private String prix;
#SerializedName("pseudo")
private String pseudo;
#SerializedName("telContact")
private String telContact;
#SerializedName("titre")
private String titre;
#SerializedName("ville")
private String ville;
public String getCp() {
return cp;
}
public void setCp(String cp) {
this.cp = cp;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmailContact() {
return emailContact;
}
public void setEmailContact(String emailContact) {
this.emailContact = emailContact;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String[] getImages() {
return images;
}
public void setImages(String[] images) {
this.images = images;
}
public String getPrix() {
return prix;
}
public void setPrix(String prix) {
this.prix = prix;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getTelContact() {
return telContact;
}
public void setTelContact(String telContact) {
this.telContact = telContact;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
#Override
public String toString(){
return "Post{" +
"id='" + getId() + '\'' +
", titre='" + getTitre() + '\'' +
", description='" + getDescription() + '\'' +
", prix='" + getPrix() + '\'' +
", pseudo='" + getPseudo() + '\'' +
", emailContact='" + getEmailContact() + '\'' +
", telContact='" + getTelContact() + '\'' +
", ville='" + getVille() + '\'' +
", cp='" + getCp() + '\'' +
", image='" + getImages() + '\'' +
", date='" + getDate() + '\'' +
'}';
}}
Here is my Retrofit Instance :
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
.build();
Here is my API Service Interface :
public interface APIService {
#POST("/android-api")
#FormUrlEncoded
Call<Post> savePost(#Field("apikey") String apikey,
#Field("method") String method,
#Field("titre") String title,
#Field("description") String description,
#Field("prix") String prix,
#Field("pseudo") String pseudo,
#Field("emailContact") String emailContact,
#Field("telContact") String telContact,
#Field("ville") String ville,
#Field("cp") String cp,
#Field("images") String[] images
);}
And here is my sendPost method :
public void sendPost(String title, String prix, String cp, String ville, String description) {
// On récupère ici les préférences de l'utilisateur
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String pseudo = preferences.getString("pseudo", "DEFAULT");
String emailContact = preferences.getString("mail", "DEFAULT");
String telContact = preferences.getString("tel", "DEFAULT");
// Provisoire
String[] images = {} ;
mAPIService.savePost(APIKEY,METHOD,title,description,prix,pseudo,emailContact,telContact,ville,cp,images).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("SUCCESS", "test : "+ response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Log.e("FAIL", "Unable to submit post to API.");
}
});}
Thank you in advance for helping me
I recently used retrofit to retrieve data...
First used http://www.jsonschema2pojo.org/ to create a model class from your possible outcome JSON response .
And I used Retrofit instance--
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client =
new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
I've tried pass object between activities exactly like in How to pass an object from one activity to another on Android
and SerializableTask is creating correctly but when I want to read this in next activity it is null.
Task task = listOfTask.get(position);
Log.i(TAG, "recyclerViewEditTask: edit clicked for title: " +
task.getTitle());
SerializabledTask sTask = new SerializabledTask(task.getTitle(),
task.getDetails(), task.getTimeToDo(), task.getTag(),
task.getId(), task.isDone());
if(sTask == null)
Log.e(TAG, "recyclerViewEditTask: sTask IS NULL");
else {
Log.i(TAG, "recyclerViewEditTask: sTaskInfo: " + sTask.toString());
Intent editIntent = new Intent(ListOfTasksActivity.this, EditTaskActivity.class);
editIntent.putExtra("task", sTask);
startActivity(editIntent);
then it goes to another activity
activity that try to get Serializable object:
Intent i = getIntent();
SerializabledTask sTask = (SerializabledTask) i.getSerializableExtra("task");
if(sTask == null)
Log.e(TAG, "onCreate: sTASK IS NULL" );
and "onCreate: sTASK IS NULL" is calling
when I tried to pass single String it works properly
Serializables class:
public class SerializabledTask implements Serializable {
String title, details, timeToDo, tag;
int id;
boolean done;
Task task;
public SerializabledTask(String title, String details, String timeToDo, String tag, int id, boolean done) {
this.title = title;
this.details = details;
this.timeToDo = timeToDo;
this.tag = tag;
this.id = id;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getTimeToDo() {
return timeToDo;
}
public void setTimeToDo(String timeToDo) {
this.timeToDo = timeToDo;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
#Override
public String toString() {
return "SerializabledTask{" +
"title='" + title + '\'' +
", details='" + details + '\'' +
", timeToDo='" + timeToDo + '\'' +
", tag='" + tag + '\'' +
", id=" + id +
", done=" + done +
", task=" + task +
'}';
}
Your model class SerializableTask must implement Serializable for your code to work.
public class SerializableTask implements Serializable {
...
}
Also it's highly recommended to use Parcelable instead of Serializable, because it's a lot faster.
Source : http://www.developerphil.com/parcelable-vs-serializable/
I am getting this error when querying a URL and get a json object. My json:
{"status":1,"username":"admin","nombre":"Username","email":"example#example.cl","codigo_usuario":"1","hash":"2938632bfdklsngh","imagen":"05c151584cc1e9aa2985b5bd0a3a4cd2.jpeg"}
Create the User class
public class User {
private int status;
private String username;
private String nombre;
private String email;
private String codigo_usuario;
private String hash;
private String imagen;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
public String getCodigo_usuario() {
return codigo_usuario;
}
public void setCodigo_usuario(String codigo_usuario) {
this.codigo_usuario = codigo_usuario;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [status=" + status + ", username=" + username
+ ", nombre=" + nombre + ", email=" + email
+ ", codigo_usuario=" + codigo_usuario + ", hash=" + hash
+ ", imagen=" + imagen + "]";
}
}
And in my class, I make the request to the URL I have this code:
public static boolean authenticate(String username, String password){
boolean error = false;
User user = null;
try {
String request = Config.getText("URL_BASE")+Config.getText("URL_AUTHENTICATE")+username+"/"+password;
HttpURLConnection conn = (HttpURLConnection) new URL(request).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new Exception("Failed : HTTP error code : " + conn.getResponseCode());
}
user = new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class);
System.out.println(user.toString());
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
And I get the exception. I saw other post with this same error and in most the error was the json format or class that did not have the same fields. Now, check well and everything should be OK. But for some reason I receive this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at controller.WService.authenticate(WService.java:29)
at view.Login._verificarLogin(Login.java:77)
at view.Login$2.actionPerformed(Login.java:44)
I'm new to Java and try to consume a web service for data and use. I think this is my best option but still do not understand the error.