Nick
Nick

Reputation: 135

Android : YelpAPI access error

I want to display a list of restaurants using my current location from Yelp API.There is very little or no clear help on this. I am trying various possible ways to get the result but not able to get it. I am just a beginner in Android.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'. com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/codec/BinaryDecoder.class

The flow should be like on the MainActivityFragment it should display a list of Restaurants in one mile radius from my current location.

MAWFragment.java class

package com.nickdroid.projectmaw;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.yelp.clientlib.connection.YelpAPI;
import com.yelp.clientlib.connection.YelpAPIFactory;
import com.yelp.clientlib.entities.SearchResponse;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

;

/**
 * A placeholder fragment containing a simple view.
 */
public class MAWFragment extends Fragment {

    public static final String LOG_TAG = "MAWFragment";
    private ArrayAdapter<String> adapter;
    /*final String CONSUMER_KEY = "xxxxxxxxxxxxxx";
    final String CONSUMER_SECRET = "xxxxxxxxxxxxxx";
    final String TOKEN = "xxxxxxxxxxxxxxx";
    final String TOKEN_SECRET = "xxxxxxxxxxxxxxxxx";*/

    final String YELP_BASEURL="https://api.yelp.com/v2/search?";
    final String Y_TERM = "term";
    final String Y_LOCATION = "location";
    final int Y_LIMIT = 10;

    public MAWFragment() {
    }


    @Override
    public void onStart() {
        super.onStart();

    }



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        /*String[] weeksWeather = {"sunny","cloudy","hot","sleet","volcanic ash","windy","tornado","tsunami","breezy"};
        ArrayList<String> weatherArray = new ArrayList<String>(Arrays.asList(weeksWeather));
*/
        YelpAPIFactory apiFactory = new YelpAPIFactory(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET, BuildConfig.TOKEN, BuildConfig.TOKEN_SECRET);
        YelpAPI yelpAPI = apiFactory.createAPI();
        Map<String, String> params = new HashMap<>();

        // general params
        params.put("limit", "10");
        // locale params
        params.put("lang", "en");

        try {
            Call<SearchResponse> call = yelpAPI.getPhoneSearch("San Francisco", params);
            SearchResponse searchResponse = call.execute().body();
        }catch(Exception ioEception){
            ioEception.printStackTrace();
        }

        final ListView listView = (ListView)rootView.findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(getActivity(),R.layout.fragment_main,R.id.item_text,new ArrayList<String>());


        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int itemPosition = position;
                String itemValue = (String) listView.getItemAtPosition(position);

                Toast.makeText(getActivity(), "ListItem : " + itemValue, Toast.LENGTH_SHORT).show();
            }
        });
        return rootView;
    }

    OAuthService service;
    Token accessToken;

    /*public MAWFragment(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.service = new ServiceBuilder().provider(TwoStepOAuth.class).apiKey(consumerKey).apiSecret(consumerSecret)
                .build();
        this.accessToken = new Token(token, tokenSecret);
    }*/

    public String searchForBusinessesByLocation(String term, String location) {
        OAuthRequest request = createOAuthRequest(YELP_BASEURL);
        request.addQuerystringParameter("term", Y_TERM);
        request.addQuerystringParameter("location", Y_LOCATION);
        request.addQuerystringParameter("limit", String.valueOf(Y_LIMIT));
        return sendRequestAndGetResponse(request);
    }


    private OAuthRequest createOAuthRequest(String path) {
        OAuthRequest request = new OAuthRequest(Verb.GET, path);
        return request;
    }

    private String sendRequestAndGetResponse(OAuthRequest request) {
        System.out.println("Querying " + request.getCompleteUrl() + " ...");
        this.service.signRequest(this.accessToken, request);
        Response response = request.send();
        return response.getBody();
    }

    public class FetchMealsTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... data) {

        return null;
        }

    }
    }

MainActivity.java

package com.nickdroid.projectmaw;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.nickdroid.niket.projectmaw"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }

    buildTypes.each {
        it.buildConfigField 'String', 'CONSUMER_KEY', MyYelpMAWApiKey
        it.buildConfigField 'String', 'CONSUMER_SECRET', MyYelpMAWSecretKey
        it.buildConfigField 'String', 'TOKEN', MyYelpMAWToken
        it.buildConfigField 'String', 'TOKEN_SECRET', MyYelpMAWSecretToken
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile files('libs/scribe-1.3.0.jar')
    compile files('libs/commons-codec-1.7.jar')
    compile files('libs/yelp-android-2.0.0.jar')
    compile 'se.akerfeldt:okhttp-signpost:1.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
    compile 'oauth.signpost:signpost-core:1.2.1.2'
    compile files('libs/converter-jackson-2.0.0.jar')
    compile 'com.android.support:multidex:1.0.0'
    compile files('libs/retrofit-2.0.2.jar')
}

android {
    configurations{
        all*.exclude module: 'commons-codec-1.7.jar'
    }
}

gradle.properties

# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

MyYelpMAWApiKey = "xxxxxxxxxxxxxx"
MyYelpMAWSecretKey = "xxxxxxxxxx"
MyYelpMAWSecretToken = "xxxxxxxxx"
MyYelpMAWToken = "xxxxxxxxx"

Upvotes: 3

Views: 345

Answers (1)

Ezra
Ezra

Reputation: 150

I was able to deal with this as follows:

  • To resolve the collision, I removed the Apache JAR that I had in my project.
  • To ensure that the required libs got re-added correctly, I added this line to build.gradle, under "android":

    useLibrary 'org.apache.http.legacy'
    
  • To deal with a different collision of a file I did not need, I added this section also under "android":

    packagingOptions {
        exclude 'META-INF/maven/oauth.signpost/signpost-core/pom.properties'
    }
    

Then my project built.

Upvotes: 1

Related Questions