How do I pass JSON data to CalenderView onSelectedDayChange()? - retrofit2

I want to pass the data from the API (called using Retrofit) to calendar date onClick() event (onSelectedDayChange).
public class MainActivity extends AppCompatActivity {
List<APIData> dataList;
private CalendarView mCalendarView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalendarView= findViewById(R.id.calendarView);
Calendar rightNow = Calendar.getInstance();
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
month = 1+month;
Toast.makeText(getApplicationContext(), ""+year+"-"+month+"-"+dayOfMonth,Toast.LENGTH_SHORT).show();
}
});
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<APIData> call = apiInterface.gethistorydetails("s10-1", "2018-08-01");
call.enqueue(new Callback<APIData>() {
#Override
public void onResponse(Call<APIData> call, Response<APIData> response) {
Log.d("TAG",response.code()+"");
APIData apiData = response.body();
}
#Override
public void onFailure(Call<APIData> call, Throwable t) {
}
});
}
}
As you can see in this pic, there are 4 different fields where I need to show data called from API. So whenever I click any dates on the calendar, the respective data from API should fill up the fields.

Assuming you are having all the 4 dates from APIData object. Convert the date(2018-09-09) into timeInMillis and set the date into calendarView on click of respective date fields:-
bus_arrival.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCalendarView.setDate(timeInMillis);
}
});
check_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCalendarView.setDate(timeInMillis);
}
});

In this use case you have to call the api every time whenever you change the date in calendar, This api will give you data in its response, simply set this data in your fields.
There are few steps to follow.
1- In datePicker dailog's onSelectedDayChange method you are getting "int year, int month, int dayOfMonth". Convert these fields into that date format that your API can understand.
To know how to convert these fields into date format follow this link
Creating java date object from year,month,day
2- Now call this APi , this api will return you result of those 4 fields in its response.
3- Simply display this data on those fields.
You code will be liked that
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
Calendar cal= Calendar.getInstance();
cal.set(year, month - 1, dayOfMonth, 0, 0);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date=format.formate(cal.getTime());
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<APIData> call = apiInterface.gethistorydetails("s10-1", date);
call.enqueue(new Callback<APIData>() {
#Override
public void onResponse(Call<APIData> call, Response<APIData> response) {
Log.d("TAG",response.code()+"");
APIData apiData = response.body();
// Here you will get data from this api and display it on your required fields
}
#Override
public void onFailure(Call<APIData> call, Throwable t) {
}
});

Related

How to showing response string in a textview?

Result: {"Status":"OK","Message":"Report Genarated.","Result":"JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL0ZvbnQvU3VidHlw"}
I am getting these response from the post api calling.Now How can i am get the Result string value.
Code:
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager = new UtilityBillManager(context, AppBaseController.get().getUserSettings());
manager.UserTransactionReceiptReport(listener,billReceiptReport); //This the api calling
}
});
}
private final TransactionReportListener listener = new TransactionReportListener() {
#Override
public void didFetch(UserReportResponse response, String message) {
}
#Override
public void didError(String message) {
}
};
UserReponse is a Model which have String status,message, result.
Just use getResult() getter of Model class
See the below code
// add this condition to prevent app crashing.
if (response.body().getResult()!=null){
textView.setText(response.body().getResult()); // getResult() is your getters of the Model Class.
}
Hope it helps.

TextWatcher in Android not setting values in other edittexts

I have three edittext values for which i am using textwatcher to update data.
I want that if i enter any value in anyone of the edit text then according to that value it should calculate and then update the edittext in which i entered the value automatically and after that set the value in other specif edit text and save the final value in string if need to send to any server.
//My Code
public class Land_details extends AppCompatActivity {
EditText land_acre_edit;
EditText land_kanal_edit;
EditText land_marla_edit;
Button land_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_land_details);
land_acre_edit = findViewById(R.id.land_acre_edit);
land_kanal_edit = findViewById(R.id.land_kanal_edit);
land_marla_edit = findViewById(R.id.land_marla_edit);
land_button = findViewById(R.id.save_land_detail);
land_acre_edit.addTextChangedListener(mytext_watcher);
land_marla_edit.addTextChangedListener(mytext_watcher);
land_kanal_edit.addTextChangedListener(mytext_watcher);
}
private TextWatcher mytext_watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String check_marla = land_marla_edit.getText().toString();
String check_kanal = land_kanal_edit.getText().toString();
String check_acre = land_acre_edit.getText().toString();
if (check_marla != null) {
if ((Integer.valueOf(check_marla) > 8)) {
check_acre =(String.valueOf(Integer.valueOf(check_kanal) + (Integer.valueOf(land_marla) / 20)));
check_marla=( String.valueOf(Integer.valueOf(land_marla) % 20));
check_acre = String.valueOf(check_acre) + (Integer.valueOf(check_kanal) / 8);
check_kanal = String.valueOf(Integer.valueOf(check_kanal) % 8);
land_marla_edit.setText(check_marla);
land_kanal_edit.setText(check_kanal);
land_acre_edit.setText(check_acre);
}}
}catch (NumberFormatException e){
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I have tried to set my try catch code in aftertextChanged but at first it was giving me numberformatexception as soon as i enter a text above my contion my app crash but after that i tried using try catch to catch a numberformatexception after that i am able to add number above my condition and even after a long wait nothing happen can any one explain where i am going wrong.

Where are the time and date pickers in Android Studio 3.1.1?

I just upgraded to Android Studio 3.1.1 and now I can't find the time nor the date pickers.
I'm running on a Linux machine, and the upgrade was suggested by Android Studio and I just clicked OK.
Below is a screenshot of my palette:
Any idea where I can find them? I'm looking for these two guys:
Thanks!
I think what are you looking for is DatePickerDialog and TimePickerDialog.
You can add it programmatically. In this example onclick edittext event.
For DatePickerDialog :
final Calendar myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String myFormat = "dd/MM/yyyy"; //set date format
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
YourDateEditText.setText(sdf.format(myCalendar.getTime()));
}
};
YourDateEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(YourActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
For TimePickerDialog :
YourTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(YourActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
YourTimeEditText.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});

How can I return data in method from Retrofit i am confused?

I am confused please can you help me? I read similar questions but its is not clear for me, thanks in advance for your patient and attention.
I want to return to onCreate data which retrieved from API call using Retrofit. Here is my function where i call Retrofit.
private void loadTimeZoneAPI(double latitude, double longitude, long timestamp, String apiKeyTz) {
String lat = Double.toString(latitude);
String lon = Double.toString(longitude);
String time = Long.toString(timestamp);
serviceTZ.getDataTZ(lat+","+lon, time, apiKeyTz).enqueue(new Callback<TimeZoneGoogle>() {
#Override
public void onResponse(Call<TimeZoneGoogle> call, Response<TimeZoneGoogle> response) {
TimeZoneGoogle result = response.body();
timeZone = result.getTimeZoneId();
}
#Override
public void onFailure(Call<TimeZoneGoogle> call, Throwable t) {
}
});
}
How i will return timeZone value to onCreate where i will use for calculation.
You need a callback listener for your data in MainActivity or any activity you have used for view.
for example:make interface like this
interface RetrofitListener{
onDataLoad(TimeZoneGoogle timeZoneGoogle);
}
then give a reference in Activity from which you are calling Retrofit class
public class ActivityTest extends AppCompatActivity implements ActivityTest.RetrofitListener {
RetrofitCall retrofitListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
retrofitListener = new RetrofitCall(this);
}
}
and here in RetrofitCall class
private class RetrofitCall {
private RetrofitListener retrofitListener;
public RetrofitCall(RetrofitListener retrofitListener) {
this.retrofitListener = retrofitListener;
}
void getData(){
getDataTZ(lat+","+lon, time, apiKeyTz).enqueue(new Callback<TimeZoneGoogle>() {
#Override
public void onResponse(Call<TimeZoneGoogle> call, Response<TimeZoneGoogle> response) {
TimeZoneGoogle result = response.body();
timeZone = result.getTimeZoneId();
}
#Override
public void onFailure(Call<TimeZoneGoogle> call, Throwable t) {
}
});
}
}

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

Resources