"&minus" instead of "-" in TextView which setting text from JSON - java

I have weather app, which is get weather information json from here:
http://icomms.ru/inf/meteo.php/?tid=44
There's a minus in "temp" value (for ex. : "temp":"−16"), and when I get value from json with retrofit2 and show it in textview it shows −16 instead of -16
How I can show -16 instead of −16?
Fragment from RecyclerViewAdapter (I use it to show weather info for multiply days), where I set text to textview
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Meteo meteo = data.get(position);
holder.date.setText(meteo.date);
holder.tod.setText(meteo.tod);
holder.pressure.setText(meteo.pressure);
// THIS IS TEMPERATURE SETTING TEXT LINE
holder.temp.setText(meteo.temp);
holder.humidity.setText(meteo.humidity);
holder.wind.setText(meteo.wind);
holder.cloud.setText(meteo.cloud);
}
Weather data class:
public class Meteo {
public String date;
public String tod;
public String pressure;
public String temp;
public String humidity;
public String wind;
public String cloud;
}
Response body:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIService.HOST)
.addConverterFactory(GsonConverterFactory
.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<List<Meteo>> call = apiService.getMeteo(44);
call.enqueue(new Callback<List<Meteo>>() {
#Override
public void onResponse(Call<List<Meteo>> call, Response<List<Meteo>> response) {
MeteoAdapter adapter = new MeteoAdapter(response.body());
// Method show just shows list of weather data
getViewState().show(adapter);
}
#Override
public void onFailure(Call<List<Meteo>> call, Throwable t) {
Log.d("MyLog", "WRONG");
}
});

Try this. I use it for formatting html tags in a textview:
String s = Html.fromHtml("−16");
tv.setText(s);
Reasoning: It sets the text as a Spanned object, rather than a string.
Note: Cannot test this currently, sorry if it doesnt work.

Related

How to display value in multiple textviews using GET method in android?

What I am trying to do is, fetch the datas from server using GET method and display them in multiple textfields.
I have already made model class, interface and created constructor, but still the app throws onFailure message.
TextView name;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String url="https://jsonplaceholder.typicode.com/";
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
name = view.findViewById(R.id.proName);
name.setText("");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceHolderApi placeHolderApi = retrofit.create(PlaceHolderApi.class);
Call<List<profileDetails>> call = placeHolderApi.getDetails();
call.enqueue(new Callback<List<profileDetails>>() {
#Override
public void onResponse(Call<List<profileDetails>> call, Response<List<profileDetails>> response) {
List<profileDetails> data=response.body();
**for (int i=0; i<data.size();i++)
name.append("Aa"+ data.get(i).getTitle());**
}
#Override
public void onFailure(Call<List<profileDetails>> call, Throwable t) {
Toast.makeText(getContext(),"nah it",Toast.LENGTH_LONG).show();
}
});
}
}
The result you are getting is a json object so try to create a model class having a data member of type List and making a call of type List make a call of that model type. This may resolve your issue.

how to store json array response using retrofit

I want to call an api endpoint and display the associated response in my android app.
The api takes a parameter user_name and return response of that user.
Response is in json array consisting json of date, location and img (base64).
RESPONSE
[
{
"id": "602a1901a54781517ecb717c",
"date": "2021-02-15T06:47:29.191000",
"location": "mall",
"img": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCASvBLADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/
}
]
the issue I am facing is I am not able to store the response and parse it.
I am using retrofit for this.
There is no issue in the api call the server gets a successfull request the issue is in the client side (android app).
Here is the code that i currently have.
ApiInterface.java
interface ApiInterface {
#FormUrlEncoded
#POST("end_point")
Call<List<Task>>getstatus(#Field("user_name") String user_name);
}
Task.java
public class Task {
#SerializedName("user_name")
public String user_name;
public Task(String user_name) {
user_name = user_name.substring(1, user_name.length()-1);
this.user_name= user_name;
}
public String getUser() {
return user_name;
}
}
MainActivity.java
private void LoginRetrofit(String user_name) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.build();
final ApiInterface request = retrofit.create(ApiInterface.class);
Call<List<Task>> call = request.getstatus(user_name);
Toast.makeText(getApplicationContext(), "user_name" + " " + call.request(), Toast.LENGTH_LONG).show();
call.enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
try {
List<Task> rs=response.body();
Toast.makeText(getApplicationContext(), "Response" + " "+rs, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.d("REsponse error",e.getMessage());
}
}
#Override
public void onFailure(Call<List<Task>> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
This is the response which is being returned.
In MainActivity.java file, update the code as below as you are printing rs object in your toast message, it prints only the object address not the value in it. So to print the value of the object you received, you must call the methods of the object to get value like as.
MainActivity.java
private void LoginRetrofit(String user_name) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.build();
...
call.enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
try {
List<Task> rs=response.body();
if(rs.size() > 0){
Task user = rs.get(0);
String id = user.getId();
String location = user.getLocation();
Toast.makeText(getApplicationContext(),"Response : Id="+id+" and location="+location, Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("REsponse error",e.getMessage());
}
}
...
});
}
and update the Task model as
Task.java
public class Task {
#SerializedName("id") public String id;
#SerializedName("date") public String date;
#SerializedName("location") public String location;
#SerializedName("img") public String img;
public Task(String id, String date, String location, String img) {
this.id=id;
this.date=date;
this.location=location;
this.img=img;
}
public String getId(){ return this.id; }
public String getDate(){ return this.date; }
public String getLocation(){ return this.location; }
public String getImg(){ return this.img; }
}
Your data model class variables should be serialized or to have names as same as in the response , so that retrofit can be able to bind response values to your model variables .
Also you must have a variable in your model class for each key-value pair in your response that you want to use .
check this example to get how retrofit really work .

Android Firestore set limit to 1 vote per user

I'm creating my first app from scratch which is a forum app on android and I've gotten to the upvoting/downvoting part of it.
I have it set up to where my users can upvote downvote (similar to StackOverflow) however I don't know how to limit it to one vote per user.
I'm using Firebase-Firestore as a DB.
I have the upvote and downvote toggle buttons set to update the score in firestore on a button click listener in with their respective selector item.xml for each.
Could anyone shed any light on an approach to limiting a user to one vote per answer per user similar to stack overflow?
Any and all help is appreciated.
edit
Current Code before trying provided answers.
AnswerAdapter
public class AnswerAdapter extends FirestoreRecyclerAdapter<Answer, AnswerAdapter.AnswerHolder> {
private QuestionAdapter.OnItemClickListener listener;
private Context mContext;
private static final String TAG = "AnswerAdapter";
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public AnswerAdapter(#NonNull FirestoreRecyclerOptions<Answer> options) {
super(options);
}
#NonNull
#Override
public AnswerHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.answer_item, viewGroup, false);
return new AnswerHolder(v);
}
#Override
protected void onBindViewHolder(#NonNull final AnswerAdapter.AnswerHolder answerHolder, final int position, #NonNull final Answer model) {
answerHolder.answerItemTextView.setText(model.getAnswer());
answerHolder.answerAuthorTextView.setText(model.getAuthor());
answerHolder.answerTimeStampTextView.setText(model.getTimestamp());
answerHolder.answerScoreTextView.setText(getSnapshots().getSnapshot(position).get("answerScore").toString());
answerHolder.mAnswerUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO: 2019-07-26 check order of operations. seems to go through upvote and then also through downvote unchecking state
if (answerHolder.mAnswerUpVoteButton.isChecked()){
answerUpVote(answerHolder, position, model);
} else {
// answerDownVote(answerHolder, position, model);
}
}
});
public class AnswerHolder extends RecyclerView.ViewHolder{
TextView answerItemTextView;
TextView answerScoreTextView;
ToggleButton answerCheckMark;
TextView answerAuthorTextView;
TextView answerTimeStampTextView;
ToggleButton mAnswerUpVoteButton;
ToggleButton mAnswerDownVoteButton;
public AnswerHolder(#NonNull final View itemView) {
super(itemView);
answerItemTextView = itemView.findViewById(R.id.answerItemTextViewId);
answerScoreTextView = itemView.findViewById(R.id.questionScoreId);
answerCheckMark = itemView.findViewById(R.id.answerCheckMarkId);
answerAuthorTextView = itemView.findViewById(R.id.answerAuthorTextViewId);
answerTimeStampTextView = itemView.findViewById(R.id.answerTimeStampTextViewId);
mAnswerUpVoteButton = itemView.findViewById(R.id.answerUpVoteId);
mAnswerDownVoteButton = itemView.findViewById(R.id.answerDownVoteId);
mContext = itemView.getContext();
}
}
private void answerUpVote(#NonNull final AnswerAdapter.AnswerHolder answerHolder, final int position, #NonNull final Answer model) {
final String answerScoreFBValue = getSnapshots().getSnapshot(position).get("answerScore").toString();
final String answerFirebaseIdString = getSnapshots().getSnapshot(position).get("answerFirebaseId").toString();
// Toast.makeText(mContext, "upvote button clicked " + answerScoreFBValue, Toast.LENGTH_SHORT).show();
final CollectionReference answerCollectionRef = FirebaseFirestore.getInstance().collection("Answers");
final DocumentReference answerDocRef = answerCollectionRef.document(answerFirebaseIdString);
answerDocRef.update("answerScore", FieldValue.increment(1)).addOnSuccessListener(new OnSuccessListener<Void>() {
// answerRef.document().update("answerscore", answerScoreTestInt).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: answerScore incremented");
// answerHolder.answerScoreTextView.setText("testing");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "onFailure: answerScore was not incremented", e);
}
});
}
Answer.java
package com.example.stairmaster.models;
public class Answer {
private String answer;
private String comment;
private String timestamp;
private int answerScore;
private String author;
private String answerFirebaseId;
private String parentQuestionId;
public Answer(String answer, String timeStamp, String author, String parentQuestionId, int answerScore) {
this.answer = answer;
this.timestamp = timeStamp;
this.answerScore = answerScore;
this.author = author;
this.parentQuestionId = parentQuestionId;
}
public Answer () {
// public no-arg constructor needed
}
public String getAnswerFirebaseId() {
return answerFirebaseId;
}
public void setAnswerFirebaseId(String answerFirebaseId) {
this.answerFirebaseId = answerFirebaseId;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public int getAnswerScore() {
return answerScore;
}
public void setAnswerScore(int answerScore) {
answerScore = answerScore;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getParentQuestionId() {
return parentQuestionId;
}
public void setParentQuestionId(String parentQuestionId) {
this.parentQuestionId = parentQuestionId;
}
}
You might consider modifying your database tables in your firebase database to look like the following.
user_votes:
- userid: 1234232 // A sample user id for your user
- forumid: 8769765 // The id of the forum or blog
- upvote: 1 // Number of upvotes in that specific forum/blog
- downvote: 0 // Number indicates the downvote to that forum/blog
- forumid: 1233432
- upvote: 1
- downvote: 0
- forumid: 8712169767
- upvote: 0
- downvote: 1
And the other table which keeps the record of upvotes/downvotes for a specific forum/blog might look like the following.
all_votes:
- forumid: 8769765 // The id of the forum or blog
- upvote: 9876 // Number of upvotes in that specific forum/blog
- downvote: 123 // Number indicates the downvote to that forum/blog
- forumid: 1233432
- upvote: 87
- downvote: 12
- forumid: 8712169767
- upvote: 112
- downvote: 10
Now, based on these two tables, you can easily decide if you are going to issue a setValue command in your all_votes table for a forum id. If the user is found to have issued an upvote already, then make the application logic in such a way that it does not issue another upvote in the all_votes table for that specific user.
Hope that helps!
I am working on a similar thing and the way I did it was using a local room database. So first, it checks the local database to see if the user can vote. If they can, then it sends a request to firestore to update the associated field. I am also using RxKotlin and wrapping the returned Task<> (from the request to firestore) into an observable. If the observable completes without any error, then it updates the local database. If it fails, then it doesn't do anything. I am sure there are other methods out there but this is how I chose to do it.

Espresso: Getting a text value from a textview and storing in a String?

I wanted to assert a part of the 'text' i get from a textview and later store it in a string, but not sure how i am going to do this.
Following is the code snippet for reference :
private void validateFlightOverviewWidgetDate(int resId, String value, boolean outBound) throws Throwable {
if (ProductFlavorFeatureConfiguration.getInstance().getDefaultPOS() == PointOfSaleId.UNITED_STATES) {
onView(allOf(outBound ? isDescendantOfA(withId(R.id.package_outbound_flight_widget))
: isDescendantOfA(withId(R.id.package_inbound_flight_widget)),
withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
withId(resId)))
.check(matches(withText(containsString("Dec 22 "))));
I want to store the value of "Dec 22" in a string so that later i can use it for assertion.
You may have to create a custom ViewAction to help you to get text from TextView:
public class GetTextAction implements ViewAction {
private CharSequence text;
#Override public Matcher<View> getConstraints() {
return isAssignableFrom(TextView.class);
}
#Override public String getDescription() {
return "get text";
}
#Override public void perform(UiController uiController, View view) {
TextView textView = (TextView) view;
text = textView.getText();
}
#Nullable
public CharSequence getText() {
return text;
}
}
Then you can get text by:
GetTextAction action = new GetTextAction();
onView(allOf(isDescendantOf(...), withId(...), withEffectiveVisibility(...)))
.perform(action);
CharSequence text = action.getText();
Though I'd not recommend to use this way for test assertion, it seems unconventional and awkward. Also, you don't really need to have isDescendantOf(...) in your allOf combination because of withId, unless the id is not unique.

How to solve 404 on Retrofit #POST on Django RESTful API?

I am able to get data from database using retrofit and REST api but facing errors in Posting data. Post works using postman but not through retrofit.I have been unable to locate the error.I have tried changing endpoint, that is, "rest" and "rest/" but still get not found error.
ApiView of Post in Django RESTful api: view.py
def post(self,request):
serializer =table_restSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'results':serializer.data},status=201)
return Response(serializer.errors, status=404)
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest',views.restSerializer.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns)
serializer.py:
class table_restSerializer(serializers.ModelSerializer):
class Meta:
model = table_rest
fields = '__all__'
My android code:
Interface
public interface ApiInterface {
#GET("rest")
Call<CustomViewResponse> getJsonFromSid();
#POST("rest")
Call<CustomViewResponse> createTask(#Body CustomViewHolder task);
}
CustomViewHolder class:
public class CustomViewHolder {
#SerializedName("id")
private Integer id;
#SerializedName("tt")
private String tt;
#SerializedName("varr")
private Integer varr;
#SerializedName("edi")
private String edi;
public CustomViewHolder(String tt, Integer varr, String edi){
this.tt = tt;
this.varr = varr;
this.edi = edi;
}
public Integer getid(){
return id;
}
/*public void setid(Integer id){
this.id = id;
}*/
public String gettt()
{
return tt;
}
public void settt(String tt){
this.tt = tt;
}
public Integer getvarr(){
return varr;
}
public void setvarr(Integer varr){
this.varr = varr;
}
public String getedi(){
return edi;
}
public void setedi(String edi){
this.edi = edi;
}
}
CustomViewResponse class
public class CustomViewResponse {
#SerializedName("results")
private List<CustomViewHolder> results;
public List<CustomViewHolder> getResults(){
return results;
}
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.sid_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
ApiInterface apiService1 = ApiClient.getClient().create(ApiInterface.class);
Call<CustomViewResponse> call = apiService.getJsonFromSid();
CustomViewHolder cc = new CustomViewHolder("my task title",22,"a string");
call.enqueue(new Callback<CustomViewResponse>() {
#Override
public void onResponse(Call<CustomViewResponse> call, Response<CustomViewResponse> response) {
int statuscode = response.code();
List<CustomViewHolder> customViewHolders = response.body().getResults();
recyclerView.setAdapter(new AdapterSid(customViewHolders, R.layout.list_item_sid, getApplicationContext()));
}
#Override
public void onFailure(Call<CustomViewResponse> call, Throwable t) {
Log.e("TAG main", t.toString());
}
});
call1.enqueue(new Callback<CustomViewResponse>() {
#Override
public void onResponse(Call<CustomViewResponse> call1, Response<CustomViewResponse> respo) {
int statuscode = respo.code();
Log.d("Message", "code..."+respo.code() + " message..." + respo.message());
CustomViewResponse respon = respo.body();
if (respon == null){
Log.e("Error",""+statuscode+ "......"+ respo.message()+"....null body");
}
}
#Override
public void onFailure(Call<CustomViewResponse> call1, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
Following is my table structure:
class table_rest(models.Model):
tt = models.CharField(max_length=10,default = 12)
varr = models.IntegerField(default=30)
edi = models.CharField(max_length=1000,default='44')
def __str__(self):
return self.tt
Using postman my Json body which gets successfully saved is :
{
"tt": "hello",
"varr": 911,
"edi": "emergency. Can't find solution"
}
Please add an extra URL.
urlpatterns = [
url(r'^admin/', admin.site.urls), # Any URL starting with admin(ex: http://testdomainname.com/admin/xyz)
url(r'^rest/$',views.restSerializer.as_view()), # Any URL starting with only rest(ex: http://testdomainname.com/rest/)
url(r'^$',views.restSerializer.as_view()), # Any empty URL with '' (ex: http://testdomainname.com/)
]
First I included the url pattern as suggested by Dinesh Mandepudi. Then I made changes to my regex in retrofit. It was url issue that I was not confronting when using postman. I just added '/' at the beginning of my post regex.
public interface ApiInterface {
#GET("/rest")
Call<CustomViewResponse> getJsonFromSid();
#POST("/rest/")
Call<CustomViewResponse> createTask(#Body CustomViewHolder task);
}
Also a silly mistake is I was trying to add a string of 13 length in the database column while I had set the limit to 10.

Categories

Resources