1

Estoy actualmente desarrollando una app de noticias con FAROO Web Search, pero cuando la app busca las noticias, crashea. No creo que sea culpa de la API porque en los tests en RapidApi funciona perfectamente. Ya he añadido el permiso de internet en el Android Manifest y lo he usado en dispositivos con conexión estable. API testComo se ve en la imagen, cuando se testea el endpoint en la web no da ningún problema.

También he intentado añadir "implementation 'org.apache.httpcomponents:httpclient:4.5'" incluso excluyendo algunos archivos que generaban otros errores.

Aquí está la actividad donde se presentan las noticias

static final ArrayList<String> title_array = new ArrayList<String>();
static final ArrayList<String> notice_array = new ArrayList<String>();
static final ArrayList<String> author_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;
ProgressBar loader;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    System.out.println("Enter");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news_activity);
    list = (ListView) findViewById(R.id.listNews);
    loader = (ProgressBar) findViewById(R.id.loader);
    if(InternetAvaliable(this))
    new TheTask().execute();
}



class TheTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String str = null;

        try {
            System.out.println("Here1");

                HttpResponse<JsonNode> response = Unirest.get("https://faroo-faroo-web-search.p.rapidapi.com/api?q=food")
                        .header("X-RapidAPI-Host", "faroo-faroo-web-search.p.rapidapi.com")
                        .header("X-RapidAPI-Key", "f18432002emshe33f07d9b71559bp125dd7jsn2d9f1840345f")
                        .asJson();

                System.out.println("Here2");
                str = response.toString();

        }
        catch(UnirestException exception){exception.printStackTrace();}

        return str;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        String response = result.toString();

        try{

            JSONArray new_array = new JSONArray(response);

            for(int i = 0; i < new_array.length(); i++){

                try{
                JSONObject jsonObject = new_array.getJSONObject(i);
                if(jsonObject.getBoolean("news")) {
                    title_array.add(jsonObject.getString("title").toString());
                    notice_array.add(jsonObject.getString("kwic").toString());
                    author_array.add(jsonObject.getString("author").toString());
                }
                }catch (JSONException e){e.printStackTrace();}

            }

            adapter = new BaseAdapter2(NewsActivity.this, title_array, notice_array, author_array);
            list.setAdapter(adapter);


        } catch (JSONException e){e.printStackTrace();}
    }

}

}

Y este es el error que genera al ejecutar el método doInBackground

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.ecoapp, PID: 13944
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:353)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
    at java.util.concurrent.FutureTask.run(FutureTask.java:271)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/client/config/RequestConfig;
    at com.mashape.unirest.http.options.Options.refresh(Options.java:70)
    at com.mashape.unirest.http.options.Options.<clinit>(Options.java:46)
    at com.mashape.unirest.http.options.Options.getOption(Options.java:42)
    at com.mashape.unirest.http.HttpClientHelper.prepareRequest(HttpClientHelper.java:151)
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:131)
    at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
    at com.example.ecoapp.NewsActivity$TheTask.doInBackground(NewsActivity.java:79)
    at com.example.ecoapp.NewsActivity$TheTask.doInBackground(NewsActivity.java:67)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
    at java.lang.Thread.run(Thread.java:764) 
 Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.client.config.RequestConfig" on path: DexPathList[[zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/base.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_resources_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/lib/x86, /system/lib, /vendor/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.mashape.unirest.http.options.Options.refresh(Options.java:70) 
    at com.mashape.unirest.http.options.Options.<clinit>(Options.java:46) 
    at com.mashape.unirest.http.options.Options.getOption(Options.java:42) 
    at com.mashape.unirest.http.HttpClientHelper.prepareRequest(HttpClientHelper.java:151) 
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:131) 
    at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68) 
    at com.example.ecoapp.NewsActivity$TheTask.doInBackground(NewsActivity.java:79) 
    at com.example.ecoapp.NewsActivity$TheTask.doInBackground(NewsActivity.java:67) 
    at android.os.AsyncTask$2.call(AsyncTask.java:333) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
    at java.lang.Thread.run(Thread.java:764) 
    Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.ecoapp-ex8BePcZbze4GqsGRAKURQ==/split_lib_resources_apk.apk
    at dalvik.system.DexFile.openDexFileNative(Native Method)
    at dalvik.system.DexFile.openDexFile(DexFile.java:353)
    at dalvik.system.DexFile.<init>(DexFile.java:100)
    at dalvik.system.DexFile.<init>(DexFile.java:74)
    at dalvik.system.DexPathList.loadDexFile(DexPathList.java:374)
    at dalvik.system.DexPathList.makeDexElements(DexPathList.java:337)
    at dalvik.system.DexPathList.<init>(DexPathList.java:157)
    at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
    at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
    at com.android.internal.os.PathClassLoaderFactory.createClassLoader(PathClassLoaderFactory.java:43)

Gracias de antemano

1
  • 1
    La pregunta está escrita en un idioma diferente al idioma oficial de este sitio, que es el español, traducela por favor !
    – Jorgesys
    el 9 jul. 2019 a las 17:29

1 respuesta 1

0

Las clases apache fueron marcadas como obsoletas en Android 6 y en Android 9 fueron removidas completamente, incluso ya no podras habilitar el modo "legacy", por esta razón obtienes el mensaje de error:

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.client.config.RequestConfig"

Lo ideal es usar la clase HttpUrlConnection

Usando HttpUrlConnection y un Asynctask puedes realizar la petición GET sin problema:

    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {

            try {
                URL  url = new URL("https://faroo-faroo-web-search.p.rapidapi.com/api?q=food");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setRequestProperty("X-RapidAPI-Host", "faroo-faroo-web-search.p.rapidapi.com");
                urlConnection.setRequestProperty("X-RapidAPI-Key", "f18432002emshe33f07d9b71559bp125dd7jsn2d9f1840345f");
                urlConnection.setRequestProperty("Content-type", "application/json");

                try {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                    BufferedReader r = new BufferedReader(new InputStreamReader(in));
                    StringBuilder total = new StringBuilder();
                    String line;

                    //Obtiene contenido de la respuesta
                    while ((line = r.readLine()) != null) {
                        total.append(line).append('\n');
                    }
                    //Imprime respueta
                    Log.i("GET request", "valor respuesta: " + total.toString());
                } finally {
                    urlConnection.disconnect();
                }


            } catch (MalformedURLException e) {
                Log.e("GET request", e.getMessage() );
            } catch (IOException e) {
                Log.e("GET request", e.getMessage() );
            }

        }
    });

valor respuesta: {"results":[{"title": "Food - Wikipedia, the free encyclopedia","kwic": "consumed to provide nutritional support for the body. It is usually of plant or animal origin, and contains essential nutrients , such as fats ...","content": "","url": "https://en.wikipedia.org/wiki/Food_product","iurl": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg/220px-Good_Food_Display_-_NCI_Visuals_Online.jpg","domain": "en.wikipedia.org","author": "","news": false,"votes": "1","date": 1446944118343,"related":[]},{"title": "Food - Wikipedia, the free encyclopedia","kwic": "consumed to provide nutritional support for the body. It is usually of plant or animal origin, and contains essential nutrients , such as carbohydrates ...","content": "","url": "http://en.wikipedia.org/wiki/Food_products","iurl": "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg/260px-Good_Food_Display_-_NCI_Visuals_Online.jpg","domain": "en.wikipedia.org","author": "","news": false,"votes": "1","date": 1401170134048,"related":[]},{"title": "Food - Wikipedia","kwic": "consumed to provide nutritional support for an organism. It is usually of plant or animal origin, and contains essential nutrients , such as ...","content": "","url": "https://en.wikipedia.org/wiki/Food_and_drink","iurl": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg/1200px-Good_Food_Display_-_NCI_Visuals_Online.jpg","domain": "en.wikipedia.org","author": "","news": false,"votes": "1","date": 1506746186183,"related":[]},{"title": "FAAN Walk for Food Allergy - The Food Allergy & Anaphylaxis Network Walk for Food Allergy","kwic": "Home page of the 2011 FAAN Walk for Food Allergy","content": "","url": "http://www.foodallergywalk.org","iurl": "","domain": "www.foodallergywalk.org","author": "","news": false,"votes": "1","date": 1347609962987,"related":[]},{"title": "Chick-fil-A offers free food to celebrate Cow Appreciation Day","kwic": "Chick-fil-A offers free food to celebrate Cow Appreciation Day WPVI-TV  Moooooooooove over! Chick-fil-A is issuing a cattle call to fill your ...","content": "","url": "https://6abc.com/food/dress-as-a-cow-get-free-food-at-chick-fil-a-/5382758/","iurl": "","domain": "6abc.com","author": "","news": true,"votes": "20","date": 1562588784000,"related":[]},{"title": "Chick-fil-A Cow Appreciation Day 2019: How to get free food July 9","kwic": "Chick-fil-A Cow Appreciation Day 2019: How to get free food July 9 AL.com  Chick-fil-A Offering Free Food On Cow Appreciation Day CBS Philly ...","content": "","url": "https://www.al.com/news/2019/07/chick-fil-a-cow-appreciation-day-2019-how-to-get-free-food-july-9.html","iurl": "","domain": "www.al.com","author": "","news": true,"votes": "20","date": 1562600880000,"related":[]},{"title": "Amazon's investment in UK food delivery unicorn Deliveroo hits a major snag as antitrust authority halts ...","kwic": "Amazon's investment in British food delivery unicorn Deliveroo has been put on hold by Britain's competition regulator, the Competition and Markets ...","content": "","url": "https://www.businessinsider.com/amazon-and-deliveroo-cma-halts-investment-2019-7","iurl": "https://static2.businessinsider.com/image/5cde7ca1021b4c01bf73cf93-2400/pjimage 1.jpg","domain": "www.businessinsider.com","author": "Jake Kanter","news": true,"votes": "20","date": 1562325720000,"related":[]},{"title": "NYPD officers pay for food for woman accused of shoplifting instead of arresting her","kwic": "NYPD officers pay for food for woman accused of shoplifting instead of arresting her WPEC  'We weren't raised like that': Meet the kindhearted ...","content": "","url": "http://cbs12.com/news/nation-world/nypd-officers-pay-for-food-for-woman-accused-of-shoplifting-instead-of-arresting-her","iurl": "","domain": "cbs12.com","author": "","news": true,"votes": "20","date": 1562378200000,"related":[]},{"title": "This is the best fast-food chain in America, accor

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.