Search FlickR Photos by Tag - java

I am trying to query FlickR photos and receive a JSON response. I am using Retrofit to make the call to the FlickR API. In my code, the user enters text, which is captured via an EditText. I want to query based on this term. I am receiving the following error from Flick: "Parameterless searches have been disabled. Please use flickr.photos.getRecent instead."
public class MainActivity extends AppCompatActivity {
private EditText mSearchTerm;
private Button mRequestButton;
private String mQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchTerm = (EditText) findViewById(R.id.ediText_search_term);
mRequestButton = (Button) findViewById(R.id.request_button);
mRequestButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mQuery = mSearchTerm.getText().toString();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.flickr.com/services/rest/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<List<Photo>> call = apiInterface.getPhotos(mQuery);
call.enqueue(new Callback<List<Photo>>() {
#Override
public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
}
#Override
public void onFailure(Call<List<Photo>> call, Throwable t) {
}
});
}
});
}
//Synchronous vs. Asynchronous
public interface ApiInterface {
#GET("?&method=flickr.photos.search&api_key=1c448390199c03a6f2d436c40defd90e&format=json") //
Call<List<Photo>> getPhotos(#Query("q") String photoSearchTerm);
}
}

Based off their API docs you're looking to pass text as the #Query param instead of q. So like:
Call<List<Photo>> getPhotos(#Query("text") String photoSearchTerm);
Other things:
• Might want to hide your API Key from your post.
• Might want to wrap the code in your onClick() method with if(!TextUtils.isEmpty(mQuery)) to prevent the issue from happening again. (Could also add a TextChangeWatcher to your EditText and enable/disable the search button based on the length of the string in the EditText

Related

getting realtime data from ubidots to android app

i am doing project on ecg monitoring android app so i need to get real time data from ubidots, i manage to get latest variable value when i run app but not the all new values which will be updated continuously.So, i need help to get real time data in my app as a result my app should get data when it is updated in ubidots variable .
here is my code for getting variable:
public class MainActivity extends Activity {
private TextView ecgLevel;
String variableValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ecgLevel = (TextView) findViewById(R.id.ecg);
ApiUbidots getApi = new ApiUbidots();
getApi.execute();
}
class ApiUbidots extends AsyncTask<Integer, Void, Value[]> {
private final String API_KEY = “";
private final String VARIABLE_ID = "”;
#Override
protected Value[] doInBackground(Integer... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable ecgLevel = apiClient.getVariable(VARIABLE_ID);
Value[] variableValues = ecgLevel.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
double varValue = variableValues[0].getValue();
variableValue = (String.valueOf(varValue));
ecgLevel.setText(variableValue);
}
}
}```
Use Retrofit for hit the API after you get latest variable

How to take checked radio buttons on a user input form in Android and store the selections as a String

I have a very simple Android application (using Java) that will take user input. It has several input fields with EditTexts and Radiobuttons and a submit Button. I am not sure if I am implementing the Radiobuttons correctly.
The app compiles and runs okay, when the activity opens I can input values etc. but nothing happens when selecting the Submit button. I have tried debugging but as the app does not crash it has hard to know what is the issue.
N.B. my API, PHP scripts and database etc is working; I have working sign up / sign in activities and the POST method for my user input form is working as I have tested with Postman
public class IncidentActivity extends AppCompatActivity {
private EditText editTextStreet, editTextTown, editTextDetails;
private RadioButton btnGenUnknown, btnGenMale, btnGenFemale, btnBedUnknown, btnBedYes, btnBedNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incident);
editTextStreet = findViewById(R.id.editTextStreet);
editTextTown = findViewById(R.id.editTextTown);
btnGenUnknown = findViewById(R.id.btnGenUnknown);
btnGenMale = findViewById(R.id.btnGenMale);
btnGenFemale = findViewById(R.id.btnGenFemale);
btnBedUnknown = findViewById(R.id.btnBedUnknown);
btnBedYes = findViewById(R.id.btnBedYes);
btnBedNo = findViewById(R.id.btnBedNo);
editTextDetails = findViewById(R.id.editTextDetails);
Button button = findViewById(R.id.buttonSubmit);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
logIncident();
}
});
}
private void logIncident() {
String street = editTextStreet.getText().toString().trim();
String town = editTextTown.getText().toString().trim();
String details = editTextDetails.getText().toString().trim();
String gender;
String bedded;
if (!btnGenUnknown.isChecked()) {
if (!btnGenMale.isChecked()){
btnGenFemale.setText("Female");
gender = btnGenFemale.toString();
}
else{
btnGenMale.setText("Male");
gender = btnGenMale.toString();
}
}else{
btnGenUnknown.setText("Unknown");
gender = btnGenUnknown.toString();
}
if (!btnBedUnknown.isChecked()) {
if (!btnBedYes.isChecked()){
btnBedNo.setText("No");
bedded = btnBedNo.toString();
}
else{
btnBedYes.setText("Yes");
bedded = btnBedYes.toString();
}
}else{
btnBedUnknown.setText("Unknown");
bedded = btnBedUnknown.toString();
}
/* Logging incident using the API call */
Call<DefaultResponse> call = RetrofitClient
.getInstance()
.getApi()
.logIncident(street, town, gender, bedded, details);
/* Executing the HTTP call */
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
if(response.code() == 201){
DefaultResponse dr = response.body();
Toast.makeText(IncidentActivity.this, dr.getMsg(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(IncidentActivity.this, "Something is wrong", Toast.LENGTH_LONG).show();
}
});
}
}
On hitting the submit button the values should be stored as Strings and posted to my database
Activity layout
//Create an object for button
Button button = findViewById(R.id.submit_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Call your method from here
logIncident();
}
});

Fill an ArrayList with object from response.body

I'm using retrofit to get list of data from api. I want to save the data which I get in body.response to arrayList. I can do that and I get the items from new arrayList, but it seems that the new list are not saved. When I try to use it outside of method onResponse, I get an error
Unable to start activity... IndexOutOfBoundsException: Index 0, Size 0
The interface
public interface ServerApi {
#Headers("Accept: application/json")
#GET("cities")
Call<ArrayList<City>> getCities();
}
The activity
public class SomeActivity extends AppCompatActivity {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://url")
.addConverterFactory(GsonConverterFactory.create())
.build();
ServerApi serverApi = retrofit.create(ServerApi.class);
ArrayList<City> cityList = new ArrayList<City>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parkings);
final TextView tv1 = findViewById(R.id.tv1);
final Call<ArrayList<City>> cities = serverApi.getCities();
cities.enqueue(new Callback<ArrayList<City>>() {
#Override
public void onResponse(Call<ArrayList<City>> call, Response<ArrayList<City>> response) {
for(int i=0; i<response.body().size(); i++){
City ct = new City(response.body().get(i).getId(), response.body().get(i).getName());
cityList.add(ct);
tv1.setText(cityList.get(i).getName());
}
}
#Override
public void onFailure(Call<ArrayList<City>> call, Throwable t) {
tv1.setText("failure " + t);
}
});
TextView c1 = findViewById(R.id.c1);
c1.setText(cityList.get(0).getName());
}
}
The string tv1.setText(cityList.get(i).getName()); inside the method onResponse works well. But when I write it out of the method, the aplication fall
As it can be seen you run your code in a background thread and a few lines below you try to update your textview on the UI thread.
The background operation will take some time, therefore, by the time you try to update the TextView the cityList is empty.
Consider reading a bit more here: Consuming apis with retrofit

Android Retrofit 1.9 return ListString upon success

I searched similar questions like this but sadly I found them really confusing and also I'm still new on using Android and Retrofit.
I have a contact list JSON here
http://api.androidhive.info/contacts/
And already working List but then I wanted to handle the Retrofit process to another class so I can just call it whenever I want. I have the MainActivity calling for the UI and the RetrofitHandler which handles the success and failure method.
Here is my Main Activity
public class MainActivity extends AppCompatActivity{
//note i just simplifiend my code a little
private List<Contacts> contacts;
public String[] itemer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitHandler retrofitHandler = new RetrofitHandler();
itemer = retrofitHandler.getContacts(this);
if (itemer != null) {
Toast.makeText(MainActivity.this,itemer[0],Toast.LENGTH_SHORT).show();
}
}
And here is my HandlerClass
ublic class RetrofitHandler {
public String[] item;
public static final String ROOT_URL = "http://api.androidhive.info";
public List<Contacts> contacts;
public String[] getContacts(final Context context) {
final ProgressDialog loading = ProgressDialog.show(context, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
MainActivity update = new MainActivity();
List<Contact> contactList = contacts.getContacts();
item = new String[contactList.size()];
for (int i = 0; i < contactList.size(); i++) {
item[i] = contactList.get(i).getName();
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_LONG).show();
}
});
return item;
}
My problem is it runs smoothly with no error on LogCat. Unfortunately the Toast on the mainactivity won't appear.
Your issue is because of asynchronous nature of the request/response. Success or Failure callbacks fires upon response, which is happen in asynchronous manner. So basically your method returns before that happens, it means your item is null. You have to use synchronous mechanism or you have to check MVP pattern which gives perfect solution for your problem. See below is an example of using synchronous call (I've not tested it, but it should work).
public List<Contacts> getContacts(){
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
return api.getContacts();
}
See this tutorial to get more idea. I suggest you to move to retrofit 2 which is much more greater than retrofit 1.

Android - How to pass interface to AsyncTask

I'm trying to figure out how to create an AsyncTask that runs my php API code in the background then alerts my MainActivity once it completes. I've been reading tutorials and trying things for hours now and I'm just frustrated at this point as I can't find anywhere that answers my question.
I create the AsyncTask and it runs successfully and I can log the returned information from my API in the onPostExecute but I cannot figure out how to alert the MainActivity that the task was completed. I do not know what to pass into the creation of the APICall. Every tutorial I read shows that the AsyncTask constructor takes the interface as an argument as shown in my code below, but how do you pass an interface as an argument?
MainActivity.java (implements OnTaskCompleted)
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall( ???What do I put here?? );
api.execute("users");
}});
....
#Override
public void onTaskCompleted() {
Log.v("Play","Main Activity ON Task completed!");
OnTaskCompleted.java
public interface OnTaskCompleted {
public void onTaskCompleted();
}
APICall.java (extends AsyncTask)
public APICall(OnTaskCompleted listener){
this.listener = listener;
}
....
protected void onPostExecute(JSONObject j)
{
listener.onTaskCompleted();
}
You should pass the reference of your listener to the APICall class:
APICall api = new APICall(MainActivity.this);
Simple you can use anonymous interface instance like this.
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall(new OnTaskCompleted() {
#Override
public void onTaskCompleted() {
}
});
api.execute("users");
}});
OR you can Implement interface at class level like this
public class MainActivity extends Activity implements MainActivity.OnTaskCompleted {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall(MainActivity.this);
api.execute("users");
}});
}
#Override
public void onTaskCompleted() {
// Do your code on task complete
}
}
APICall api = new APICall( ???What do I put here?? );
What do I put here??
The one that implements your listener in this case your MainActivity
APICall api = new APICall(MainActivity.this);

Categories