GithubHelp home page GithubHelp logo

fatsecret / fatsecret4j Goto Github PK

View Code? Open in Web Editor NEW
12.0 6.0 16.0 46 KB

Java/Android Client for using Fatsecret REST API

Home Page: http://fatsecret4j.com

License: Apache License 2.0

Java 100.00%
food recipe java-client android fatsecret android-client java-8 maven-plugin

fatsecret4j's Introduction

fatsecret4j

Java/Android Client for using Fatsecret REST API

Java Client Code

You can use this library by downloading it here or by following this step -

Add this maven dependency in your pom.xml

<dependency>
	<groupId>com.fatsecret4j</groupId>
	<artifactId>fatsecret-platform</artifactId>
	<version>2.0</version>
</dependency>

Android Client Code

You can use this library by downloading it here and placing it in libs folder or by following these steps -

Add the following configuration to your build.gradle file

repositories {
	mavenCentral()
}

android {
	defaultConfig {
		minSdkVersion 24
		jackOptions {
			enabled true
		}
	}
	compileOptions {
		sourceCompatibility JavaVersion.VERSION_1_8
		targetCompatibility JavaVersion.VERSION_1_8
	}	
}

dependencies {
	compile 'com.fatsecret4j:fatsecret-platform:2.0'
	compile 'com.android.volley:volley:1.0.0'
}

Add the following line to your Android Manifest file

In order to target Android API level 24 or later, you will need to ensure that your application requests runtime permissions for internet access.

<uses-permission android:name="android.permission.INTERNET"/>

Supported methods

  • food.get()
  • foods.search()
  • recipe.get()
  • recipe.search()

You can check more documentation here.

fatsecret4j's People

Contributors

fatsecret avatar ohdihe avatar ranesr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

fatsecret4j's Issues

create a food

There doesn't seem to be any method to create a new food yet.
I'm investigating writing a Tandoori Receipts -> Fat Secret app
that would have to create receipts that don't exist yet as foods.

Help to get in-app products from Russia

I am developing an application for weight control, and I need products on demand, unfortunately, I cannot figure out the premium version, how to make the application accept Russian and return Russian products on demand. Here is my code
` public void onMyButtonClick(View view)
{
String key = "7b701fc864a94bc7a1abb55160aad2f6"; //Потребительский ключ
String secret = "64bf8c905a3b4c5ea45a67fb097bd1b1"; //Потребительский секрет
String query = find_food.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(this);
Listener listener = new Listener();

    Request req = new Request(key, secret, listener);

    //Этот ответ содержит список продуктов питания на странице № 0 этого запроса
    req.getFoods(requestQueue, query,0);

    //Этот пищевой объект содержит подробную информацию о продукте питания
    req.getFood(requestQueue, 29304L);
}


class Listener implements ResponseListener {

    ArrayList<Product> products = new ArrayList<Product>();
    ListView productList = (ListView) findViewById(R.id.productList);
    ProductAdapter adapter = new ProductAdapter( Foods.this, R.layout.list_item, products);

    @Override
    public void onFoodListRespone(Response<CompactFood> response) {
        System.out.println("TOTAL FOOD ITEMS: " + response.getTotalResults());

        List<CompactFood> foods = response.getResults();
        //Этот список содержит сводную информацию о продуктах питания

        System.out.println("=========FOODS============");
        for (CompactFood food : foods) {
            System.out.println(food.getName());
            System.out.println(food.getDescription());
            products.add(new Product(food.getName(), food.getDescription()));
            productList.setAdapter(adapter);
        }
    }



    @Override
    public void onRecipeListRespone(Response<CompactRecipe> response) {
        System.out.println("TOTAL RECIPES: " + response.getTotalResults());

        List<CompactRecipe> recipes = response.getResults();
        System.out.println("=========RECIPES==========");
        for (CompactRecipe recipe: recipes) {
            System.out.println(recipe.getName());
        }
    }

    @Override
    public void onFoodResponse(Food food) {
        System.out.println("FOOD NAME: " + food.getName());
    }

    @Override
    public void onRecipeResponse(Recipe recipe) {
        System.out.println("RECIPE NAME: " + recipe.getName());
    }
}`

Sometimes this method gives the Required result, But sometimes it gives either calorie null or Whole list Blank.

Hii,
I am using Fatsecret libraries for Search food with calories and servings of the food.
Here my code is:
public CustomResponse searchFoodItems(String query,Integer page) {
CustomResponse customResponse=null;
Response response = service.searchFoods(query,page);
//This response contains the list of food items at zeroth page for your query
SearchFoodDto searchFoodDto = new SearchFoodDto();
List searchFoods=new ArrayList();
try {
searchFoods = new ArrayList();
if(null!= response) {
int pageSize = response.getTotalResults()/response.getMaxResults();
searchFoodDto.setTotalPages(pageSize);
List compactFoods = response.getResults();
for (CompactFood compactFood :compactFoods) {
SearchFoodListDto searchFood=new SearchFoodListDto(); searchFood.setFoodName(compactFood.getName()); searchFood.setId(compactFood.getId()); searchFood.setType(compactFood.getType()); searchFoods.add(getFoodCalories(searchFood));
}
}
} catch (Exception e) {
e.printStackTrace();
}
searchFoodDto.setSearchFoodList(searchFoods);
customResponse=new CustomResponse<>(searchFoodDto,Status.SUCCESS);
return customResponse;
}
SearchFoodListDto getFoodCalories(SearchFoodListDto searchFoodListDto) {

	BigDecimal calories = BigDecimal.valueOf(0.0);
    try {
        Food food = service.getFood(searchFoodListDto.getId());
        if (null != food) {
        	for (Serving serving : food.getServings()) {     	  searchFoodListDto.setCalories(serving.getCalories());       		searchFoodListDto.setServing(Calculations.round(Double.valueOf(serving.getNumberOfUnits().toString()), 0)+serving.getMeasurementDescription());
        	}
        }
        else{
            searchFoodListDto.setCalories(calories);
        }
            
    } catch (Exception e) {
        e.printStackTrace();
    }
	return searchFoodListDto;
}

Sometimes this method gives the Required result.
But sometimes it gives either calorie null or Whole list Blank.

I am unable to fulfill my requirement.
Thanks,
Dhiraj

To make the code work for Android Version < 24

The code for the ResponseListener can be used only if Android version is 24 or above.

so instead of :

public interface ResponseListener { default public void onFoodResponse(Food food) { System.out.println("ResponseListener onFoodResponse"); } ....

if the code is like this:

public interface ResponseListener { void onFoodResponse(Food food); ....
then it can be used for Android SDK versions < 24

brand_name not parsed

First of all, great job with the simple API. It's a joy using it and setting things up was way easier than other food APIs out there! 👍

I am using version 2.0 of the library and I am calling the searchFood endpoint.
It looks like the returned result of CompactFood does not contain the brandName meaning that it's always null.

This is my proposed change in FoodUtility.parseCompactFoodJsonObject:

	public static CompactFood parseCompactFoodFromJSONObject(JSONObject json) {
		String name = json.getString("food_name");
		String url = json.getString("food_url");
		String type = json.getString("food_type");
		String description = json.getString("food_description");
		Long id = Long.parseLong(json.getString("food_id"));
                String brandName = type == "Brand" ? json.getString("brand_name") : null; // <----

		CompactFood food = new CompactFood();
		
		food.setName(name);
		food.setUrl(url);
		food.setType(type);
		food.setDescription(description);
		food.setId(id);
                food.setBrandName(brandName); // <----
		
		return food;
	}

Keep in mind that it's been a while since I last wrote some Java code 😅 , but I think it's clear what I am trying to do.
Would this change work, and if so, can you provide a fix asap?

How to use FatSecret4J for getting food calorie data

Hi,
I'm a newbie right here and I'm currently on an important project right now. I am planning for using FatSecret4J for my application. Can someone please help me and tell me how to use FatSecret4J for getting food calorie data?
Thank you

Using this library on Android

I am having some trouble integrating this library in android, although the library does not throw any exception, the FoodService(as well as other Service classes) always returns empty response.

Food are not showing when integrating with java using maven

Hello,
I am integrating FatSecret Java API in my project using maven dependency. But when I hit the getFood API so frequently it is not showing any food(It is showing only for the first time), while foods are available as I have checked with the fat secret website.
So please tell me what is the issue and how to resolve it?

Thanks

requests should be https

The test cases in Java work if RequestBuilder.APP_URL is changed from "http://platform.fatsecret.com/rest/server.api" to "https://platform.fatsecret.com/rest/server.api".

Running the test cases with JUnit, I cannot get them to pass unless I change the request builder to create https requests rather than http. I am a relatively new developer, so this may not be a necessary "fix," but it solved my issue of most requests giving null responses.

getFoods and getRecipes failing when only 1 result returned

For example, in my app I'm using :
implementation 'com.fatsecret4j:fatsecret-platform:2.0' implementation 'com.android.volley:volley:1.1.0'

I am calling req.getFoods(requestQueue, search, 0); within one food search activity and display in ListView; however, whenever the results from searching is 1 the activity fails with the following :

THIS IS FROM SEARCHING USING ---> "fbfx"

com..... E/AndroidRuntime: FATAL EXCEPTION: main Process: com......, PID: 22297 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)  Caused by: org.json.JSONException: Value {"brand_name":"Max Muscle","food_description":"Per 1 scoop - Calories: 72kcal | Fat: 0.00g | Carbs: 17.00g | Protein: 0.00g","food_id":"3577034","food_name":"FBX","food_type":"Brand","food_url":"https:\/\/www.fatsecret.com\/calories-nutrition\/max-muscle\/fbx"} at food of type org.json.JSONObject cannot be converted to JSONArray at org.json.JSON.typeMismatch(JSON.java:101) at org.json.JSONObject.getJSONArray(JSONObject.java:591) at com.fatsecret.platform.services.android.Request$1.onResponse(Request.java:182) at com.fatsecret.platform.services.android.Request$1.onResponse(Request.java:156)

I researched this more and it is coming from com/fatsecret/platform/services/android/Request.java line 182: JSONArray foodArray = foods.getJSONArray("food"); when the Request class is trying to convert a JSONObject into an array when the setup is different.

This ONLY happens when 1 result is returned, the JSON response is different than when returning more than 1 result.

For example, with 1 result using "fbfx" as a search query the result (JSON format) is:
{ "food": { "brand_name": "Max Muscle", "food_description": "Per 1 scoop - Calories: 72kcal | Fat: 0.00g | Carbs: 17.00g | Protein: 0.00g", "food_id": "3577034", "food_name": "FBX", "food_type": "Brand", "food_url": "https://www.fatsecret.com/calories-nutrition/max-muscle/fbx" }, "max_results": "50", "page_number": "0", "total_results": "1" }

Now, with 2 results using "fbf" as a search query (2 results returned) the JSON format is:
{ "food": [ { "brand_name": "Max Muscle", "food_description": "Per 1 scoop - Calories: 72kcal | Fat: 0.00g | Carbs: 17.00g | Protein: 0.00g", "food_id": "3577034", "food_name": "FBX", "food_type": "Brand", "food_url": "https://www.fatsecret.com/calories-nutrition/max-muscle/fbx" }, { "brand_name": "FGF Brands", "food_description": "Per 2.2 oz - Calories: 160kcal | Fat: 3.50g | Carbs: 28.00g | Protein: 4.00g", "food_id": "27445", "food_name": "Fabulous Flats Tandoori Naan", "food_type": "Brand", "food_url": "https://www.fatsecret.com/calories-nutrition/fgf-brands/fabulous-flats-tandoori-naan" } ], "max_results": "50", "page_number": "0", "total_results": "2" }

Notice that the difference from the 1 result to the 1> results is the "food" JSON object changes from an object (1 result) to an array with "[ ]" surrounding the multiple results...


For req.getRecipes(requestQueue, search, 0); I am getting the exact same error when only 1 result is returned. You can see this when searching "Sushi". The Request class fails again when trying to convert the JSONObject to a JSONArray.

I am no expert, but I believe both of these can be fixed with the com/fatsecret/platform/services/android/Request.java class updating how to bring in a JSONObject when only 1 result is returned both on line 182 and 214.

Please if anyone has a workaround in the meantime or if you need any more info about this issue, let me know!

Much appreciated!

Please help me get a response

Hello, I am trying to use the API in an android application. I followed your android documentation example, but I am getting the following error for each request I try to send:
[2] 2.onErrorResponse: Error:

I just need help getting a response, any help would be appreciated. I think it might have something to do with oauth, I'm probably missing something but I can't seem to figure it out. Any help would be appreciated. Here is my code:

package com.example.caloriecounterapi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import com.fatsecret.platform.model.CompactFood;
import com.fatsecret.platform.model.CompactRecipe;
import com.fatsecret.platform.model.Food;
import com.fatsecret.platform.model.Recipe;
import com.fatsecret.platform.services.android.Request;
import com.fatsecret.platform.services.android.ResponseListener;

import java.util.List;

public class MainActivity extends AppCompatActivity {

class Listener implements ResponseListener {

    @Override
    public void onFoodListRespone(com.fatsecret.platform.services.Response<CompactFood> response) {

        System.out.println("TOTAL FOOD ITEMS: " + response.getTotalResults());

        List<CompactFood> foods = response.getResults();
        // ^^ contains summary info about food item

        Log.i("===========FOODS===========", "vvvvvvvvvvvvvvvvvvv");
        for (CompactFood food: foods) {
            Log.i("onFoodListRespone!", food.getName());
        }
    }

    @Override
    public void onFoodResponse(Food food) {
        Log.i("onFoodResponse: ", food.getName());
    }
}

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String key = "I probably shouldn't post my key";
    String secret = "I probably shouldn't post my secret";
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    Listener listener = new Listener();
    //String str_response;

    String query = "pasta";

    Request req = new Request(key, secret, listener);

    //This response contains the list of food items at zeroth page for your query
    req.getFoods(requestQueue, query, 0);

    //This response contains the list of food items at page number 3 for your query
    //If total results are less, then this response will have empty list of the food items
    req.getFoods(requestQueue, query, 3);

    //This food object contains detailed information about the food item
    req.getFood(requestQueue, 29304L);


    Log.i("response!", "received");

}

}

I also tried following an example on the issues forum, but it gives me the error:

2019-06-27 09:11:15.491 30700-30700/com.example.caloriecounterapi I/System.out: Exception: Cleartext HTTP traffic to platform.fatsecret.com not permitted
2019-06-27 09:11:15.491 30700-30700/com.example.caloriecounterapi I/response!: IS NULL :(

Here is the code I used for that one:

    String key = "c92978d965e64f22bd57ad49833efd3d";
    String secret = "cc481c0751314401bc2aa6afec5755cd";
    FatsecretService service = new FatsecretService(key, secret);
    String query = "pasta";
    com.fatsecret.platform.services.Response<CompactFood> response = service.searchFoods(query);
    if (response == null) {
        Log.i("response!", "IS NULL :(");
    }

If you could give me any advice at all on how to get a response for my app, I would greatly appreciate it. Thank you for taking the time to read this and have a good day :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.