How do I display json to textviews? - android

I'm trying to display some json data to textviews. My "getTitle" getter method works fine and the data is shown in the textview widget. However when I should pass the "getDescription" getter method, it doesn't comes up for suggestion.
I would really love some help with this, or also if I'm not going about it the right way someone could point me in the right direction.
call.enqueue(new Callback<Campaign>() {
#Override
public void onResponse(Call<Campaign> call, Response<Campaign> response) {
if (response.isSuccessful()) {
String id = response.body().getId();
campaignName.setText(getTitle());
campaignDesc.setText();
} else {
Toast.makeText(StartSurveyActivity.this, "Error Retrieving Id", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Campaign> call, Throwable t) {
// Log error here if request failed
Log.e(TAG, t.toString());
}
});
}
Here is my java campaign model class. Also I thought it was important to mention that my "getDescription" getter and setter is shown in a pale greyish color while the "getTitle" getter and setter is the gold looking color. Thanks for your assistance in advance.
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSurveyUrl() {
return surveyUrl;
}
public void setSurveyUrl(String surveyUrl) {
this.surveyUrl = surveyUrl;
}
public Integer getTotalResponseCount() {
return totalResponseCount;
}
public void setTotalResponseCount(Integer totalResponseCount) {
this.totalResponseCount = totalResponseCount;
}
public String getLanguageCode() {
return languageCode;
}
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getOrganisationLogoUrl() {
return organisationLogoUrl;
}
public void setOrganisationLogoUrl(String organisationLogoUrl) {
this.organisationLogoUrl = organisationLogoUrl;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}

Try below, you are calling method on response
campaignName.setText(response.body().getDescription())

The body of the response will hold the data or response object you have defined. So to call any getter or setter method of the response object you have to use body of the response for example response.body().getDescription(), response.body().getCreated(). To show description in the TextView try this
campaignDesc.setText(response.body().getDescription())

Related

How to increment value in Firebase database android

Hopefully someone can help me with this. Lets say I have a post and I want to track down the number of clicks it gets. How do I go about incrementing the value in the database (Firebase). For example the post has one click that count as 1 then it has another click that counts as 2 then so on and so fourth. I tried doing something but I'm getting this error. I really need your help on this. Thanks in advance
Error message
Can't convert object of type java.lang.Long to type com.myapp.poopy.Model_Information
My code
databaseReference = FirebaseDatabase.getInstance("https://poopy-43981.firebaseio.com/").getReference().child("Post").child(getid);
int count;
count = count ++;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child("clicks").setValue(count+1);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Json
{
"Post" : {
"lG71ennq86UIZ5a5Oqh8oaYAXe03" : {
"-MHNWmVK3rBnvnr0qcph" : {
"clicks" : 0,
"id" : "-MHNWmVK3rBnvnr0qcph",
}
}
},
Model_class
public Model_Information(String category, String headline, String mImageUrl,String created,String time,String id,String status ) {
this.mImageUrl = mImageUrl;
this.category = category;
this.headline = headline;
this.created=created;
this.time=time;
this.id=id;
this.status=status;
}
public Model_Information() {
}
public String getstatus() {
return status;
}
public void setstatus(String status) {
status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
//Class using model class
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String previousChildName) {
if (dataSnapshot.exists()) {
progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
myUploads.clear();
Model_Information upload = postsnapshot.getValue(Model_Information.class);
myUploads.add(upload);
aAdapter = new Adapter(MainActivity2.this, myUploads);
recyclerView.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
recyclerView.invalidate();
}
}
}
To be able to update the clicks value you need to know the complete path to that value. In your use-case there seem to be two variables in that path:
the UID
a push ID
Once you know both values, increment the value can be done with the (relatively new) ServerValue.increment operation like this:
DatabaseReference rootReference = FirebaseDatabase.getInstance("https://poopy-43981.firebaseio.com/");
DatabaseReference userReference = rootReference.child("Post").child(getid);
DatabaseReference countReference = userReference.child("-MHNWmVK3rBnvnr0qcph").child("clicks");
countReference.setValue(ServerValue.increment(1));

How can I print out the results of this json file? (Android Retrofit2)

I want to show Json result in textview using retrofit2, but I can't get the desired result.
json
{
"rows" : [ {
"playerId" : "f8a49812eb9c3e5c8e738c3664e0ebd1",
"nickname" : "Yuichuan",
"grade" : 89
} ]
}
Model.class
public class Model {
public String playerId;
public String nickname;
public int grade;
public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
PlayerModel.class
public class PlayerModel {
public List<Model> rows;
}
**RetrofitFactory.class**
public class RetrofitFactory {
private static String BASE_URL="https://api.neople.co.kr/";
public static RetrofitService create(){
Retrofit retrofit=new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonC`enter code here`onverterFactory.create()).build();
return retrofit.create(RetrofitService.class);
}
}
RetrofitService.interface
public interface RetrofitService {
#GET("cy/players/")
Call<PlayerModel> getlist(#Query("nickname") String nickname,
#Query("apikey") String apikey);
}
MainActivityt
public class MainActivity extends AppCompatActivity {
private static final String API_KEY = "8yTuVMwy2DirHl2sWaZ3C8IJLslOfTpQ";
private static final String TAG ="Main" ;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.test);
RetrofitService networkService=RetrofitFactory.create();
networkService.getlist("Yuichuan",API_KEY)
.enqueue(new Callback<PlayerModel>() {
#Override
public void onResponse(Call<PlayerModel> call, Response<PlayerModel> response) {
if(!response.isSuccessful()){
textView.setText(response.code());
return;
}
Log.d(TAG, "onResponse: ConfigurationListener::"+call.request().url());
}
#Override
public void onFailure(Call<PlayerModel> call, Throwable t) {
textView.setText(t.getMessage());
}
});
}
}
I want to print out these json files, but it doesn't work as I want, so I want you to give me some help or advice.It seems like a simple problem, but it is very difficult for me because I am not used to json.
The textView.setText(response.code()); give you a code of response. To get your data model you need a body of response response.body()

How to show if a message is seen or not via using Firebase Real time Database

I want to show if a message is seen or not in my app which is using Firebase Real time Database.What i am able to till now is update it on on the database if the message is seen or not but i am not able to retrieve that value using listeners in my recyclerview Adaptor .It happens that if the last message is not seen it displays all the previous messages are not seen similarly if the last message is seen it displays all the previous messages are seen.
Database Structure
My Code for checking if the message is seen or not
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat=mChat.get(position);
holder.show_message.setText(chat.getMessage());
if (Key != null) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Chats").child(ChatKey).child(Key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Chat chat1 = dataSnapshot.getValue(Chat.class);
if (chat1.isIsseen()) {
holder.Delivered.setImageResource(R.drawable.ic_done_all_black_24dp);
} else {
holder.Delivered.setImageResource(R.drawable.ic_check_black_24dp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(eventListener);
}
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.drawable.user2);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
}
Update
Chat Class
public class Chat {
private String sender;
private String receiver;
private String message;
private boolean isseen;
private long timestamp;
String MessageId;
public Chat(String sender, String receiver, String message, boolean isseen, long timestamp) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.isseen = isseen;
this.timestamp = timestamp;
}
public Chat() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessageId() {
return MessageId;
}
public void setMessageId(String messageId) {
MessageId = messageId;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
Update2
isseen Listener
private void seenMessage(final String userid){
reference = FirebaseDatabase.getInstance().getReference("Chats").child(ChatKey);
// reference.keepSynced(true);
seenListener=new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(fuser.getUid()) && chat.getSender().equals(userid)) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
reference.addListenerForSingleValueEvent(seenListener);
}
Do this in onBindViewHolder
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat=mChat.get(position);
holder.show_message.setText(chat.getMessage());
boolean isSeen = chat.isIsseen();
if(isSeen){
//seen
holder.Delivered.setImageResource(R.drawable.ic_done_all_black_24dp);
}else{
//not seen
holder.Delivered.setImageResource(R.drawable.ic_check_black_24dp);
}
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.drawable.user2);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
}
UPDATE:
If you want to refresh the recycler view for live updates add this method under the onBindViewHolder():
#Override
public void onDataChanged() {
//refresh
yourAdapter.notifyDataSetChanged();
}

using Map to get object of custom class

I'm new at using maps, how can we get object of custom Class from Map..
i.e.
feedSendModelClass:
public class feedSendModelClass {
private String content;
private String picThumbnail;
private String picurl;
private String videourl;
private String videoThumbnail;
private String mTime;
public feedSendModelClass() {
//blank for firebase
}
public String getTime() {
return mTime;
}
public void setTime(String time) {
mTime = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(String videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
public String getVideourl() {
return videourl;
}
public void setVideourl(String videourl) {
this.videourl = videourl;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
public String getPicThumbnail() {
return picThumbnail;
}
public void setPicThumbnail(String picThumbnail) {
this.picThumbnail = picThumbnail;
}
}
Map
Map<String, feedSendModelClass> feedKeys = (Map<String,feedSendModelClass>) dataSnapshot.getValue();
Datasnapshot:
DataSnapshot { key = feedsMetaPool, value = {20160708155218759={content=bzzzhss, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081552353353553518759sahaj9917730102?alt=media&token=ce1c6e7c-28c5-442e-9405-4468bf5fc204, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20353353535355353160708155218759sahaj9917730102?alt=media&token=14d33963-f3da-4407-a08f-ab0afce21ace}, 20160708164100152={content=sj sjs skss sksssvsjm, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081641003535152sahaj9917730102?alt=media&token=323c4a27-1850-4bc9-adea-34e5319ac506, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160708164100152sahaj9917730102?alt=media&token=0b064b46-2f14-49af-b3e6-7a573f6c2d3f}, 20160708142314069={content=dadax, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F2016070rdgdg54353535358142314069sahaj9917730102?alt=media&token=19d03f11-d12f-43c1-96f5-ca397a9179c9, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160735353508142314069sahaj9917730102?alt=media&token=ab9c73eb-ec44-46ae-9daa-6fc508cb08a6} }
This has become tricky for me..Thanks..
There could be some other way round to do it through firebase
If you are asking how you retrieve the feedSendModelClass object from the map named feedKeys, then this syntax should work:
feedKeys.get(key)
The key is your String, and the object is the feedSendModelClass object. However, first you'd need to put key and value pairs into the map (so it's not empty), with feedKeys.put(key, value), where the key is a String and value is the feedSendModelClass.
If this totally doesn't answer your question, I apologize, but from your description, it is a bit difficult to understand what you need help with.
On an unrelated note, it would be more appropriate to name your class FeedSendModelClass, as per Java conventions classes start with a capital letter.
If you're using Firebase then you can use a ChildEventListener. It calls the onChildAdded() method once for every initial child in the node and everytime a new child is added. Then you can add the Object to an ArrayList directly (or do whatever you want with it)
ArrayList<feedSendModelClass> feedKeysArrayList = new ArrayList<>();
DatabaseReference feedKeysRef = FirebaseDatabase.getInstance().getReference("path/to/the/feedkeys");
feedKeysRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
feedKeysArrayList.add(dataSnapshot.getValue(feedSendModelClass.class));
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Add appropriate code
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Add appropriate code
}
});

java.util.LinkedHashMap cannot be cast to DataList

I am trying to implement the server connections with retrofit library.
Everything seems fine but when I receive the data on success callback it crashes with the below exception.
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to aandroid.com.retrofitframework.requestData.DataList
at cuiserve.com.volleyframework.activity.RetrofitActivity$1.onDataReceived(RetrofitActivity.java:18)
at cuiserve.com.volleyframework.httpConnection.ConnectionHelper.success(ConnectionHelper.java:44)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
here is the activity class making the server calls
public class RetrofitActivity extends SuperActivity {
private ConnectionHelper.ServerListener<DataList> httpListener = new ConnectionHelper.ServerListener<DataList>() {
#Override
public void onDataReceived(DataList data) {
hideProgressBar();
Log.d("ANSH",data.getBalance());
}
#Override
public void onErrorReceived(String errorMsg) {
hideProgressBar();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showProgressBar();
ConnectionHelper<DataList> helper = new ConnectionHelper<DataList>(HttpRequestConstant.LOGIN_REQUEST,httpListener);
helper.getResponse();
}
#Override
public View getLayoutResource() {
return null;
}
#Override
protected void internetAvailable() {
}
}
ConnectionHelper.class making the request
public class ConnectionHelper<T> implements Callback<T> {
private int requestType;
private ServerListener<T> listener;
public ConnectionHelper(int requestType, ServerListener listener) {
this.requestType = requestType;
this.listener = listener;
}
public void getResponse() {
switch (requestType) {
case HttpRequestConstant.LOGIN_REQUEST:
IServerConnection<T> connection = restAdapter.create(IServerConnection.class);
connection.login(this);
break;
}
}
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.json-generator.com/api")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new JacksonConverter(Mapper.get()))
.build();
#Override
public void success(T t, Response response) {
listener.onDataReceived(t);
// success callback false here with the exception
// as ClassCastException and says LinkedHashMap can not be cast to DataList(which i pass as class that the response has to be mapped to)
}
#Override
public void failure(RetrofitError error) {
}
public interface ServerListener<T> {
public void onDataReceived(T data);
public void onErrorReceived(String errorMsg);
}
}
The interface and the method with retrofit annotation
public interface IServerConnection<T> {
#GET(HttpRequestConstant.JACKSON_FETCH)
void login(Callback<T> cb);
}
The custom JacksonConverter which is my suspicion
public class JacksonConverter implements Converter {
private ObjectMapper mapper = new ObjectMapper();
public JacksonConverter(ObjectMapper objectMapper) {
this.mapper = objectMapper;
}
#Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
JavaType javaType = mapper.getTypeFactory().constructType(type);
try {
return mapper.readValue(body.in(), javaType);
} catch (IOException e) {
throw new ConversionException(e);
}
}
#Override
public TypedOutput toBody(Object object) {
try {
String charset = "UTF-8";
String json = mapper.writeValueAsString(object);
return new JsonTypedOutput(json.getBytes(charset));
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput {
private final byte[] jsonBytes;
JsonTypedOutput(byte[] jsonBytes) {
this.jsonBytes = jsonBytes;
}
#Override
public String fileName() {
return null;
}
#Override
public String mimeType() {
return "application/json; charset=UTF-8";
}
#Override
public long length() {
return jsonBytes.length;
}
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(jsonBytes);
}
}
}
and the DataList
package cuiserve.com.volleyframework.requestData;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by ansh on 5/4/15.
*/
#JsonIgnoreProperties(ignoreUnknown = true)
public class DataList extends SomeClass{
private String _id;
private int index;
private String guid;
private boolean isActive;
private String balance;
private String picture;
private int age;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now the problem is when i do it without using generics(which i have done in the code) things work fine and don't give any exception but in case of generics it fails.
Why am I getting LinkedHashMap classCastException where nothing is related to that in my code.Please help.
By using a generic parameter the actual type information is completely lost to the runtime and cannot be inferred. It essentially ends up being the same as Object. When Gson sees that you want an Object type, it uses a Map to place the JSON information in. This way, if you re-serialize that object instance the data will be retained.
You cannot use generic interfaces with Retrofit. An exception has been added when you try to do this rather than letting it fail in this manner for the next release.
Here is what I do to handle such cases:
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public abstract class ModelCallback<Model> implements Callback<Object> {
Class classOfT;
public ModelCallback(Class modelClass){
this.classOfT = modelClass;
}
#Override
public void success(Object model, Response response) {
Gson gson = new Gson();
onSuccess((Model) gson.fromJson(gson.toJson(model),classOfT));
}
#Override
public void failure(RetrofitError error) {
onError(new Exception(error.getMessage()));
}
public abstract void onSuccess(Model model);
public abstract void onError(ClyngException e);
}

Categories

Resources