Пытаюсь подключиться к гугл книгам с андроида - PullRequest
0 голосов
/ 03 ноября 2011

Давайте начнем с вершины. Я пытаюсь создать приложение, которое принимает ISBN, затем подключается к Google Книгам и оттуда получает информацию о книге. Я смог сделать это, используя обычный Java:

import java.net.URL;
import com.google.gdata.client.books.BooksService;
import com.google.gdata.client.books.VolumeQuery;
import com.google.gdata.data.books.VolumeEntry;
import com.google.gdata.data.books.VolumeFeed;
public class books 
{
public static void main(String[] args)
{       
    ////////////////////////////////////////////////
    try
    {                               
        BooksService booksService = new BooksService("UAH");
        String isbn = "9780262140874";
        URL url = new URL("http://www.google.com/books/feeds/volumes/?q=ISBN%3C" + isbn + "%3E");
        VolumeQuery volumeQuery = new VolumeQuery(url);
        VolumeFeed volumeFeed = booksService.query(volumeQuery, VolumeFeed.class);
        VolumeEntry bookInfo=volumeFeed.getEntries().get(0);

        System.out.println("Title: " + bookInfo.getTitles().get(0));
        System.out.println("Id: " + bookInfo.getId());
        System.out.println("Authors: " + bookInfo.getCreators());
        System.out.println("Description: "+bookInfo.getDescriptions()+"\n");
    }catch(Exception ex){System.out.println(ex.getMessage());}
    /////////////////////////////////////////////////                           
 }}

Я использовал jars books и клиент из \ gdata-src.java-1.46.0 \ gdata \ java \ lib с зависимостями из google-api-java-client-1.5.0-beta \ dependencies, и он работал отлично , когда я пытался преобразовать его в Android, он дал мне ошибку «Преобразование в формат Dalvik не удалось с ошибкой 1», поэтому он не будет компилироваться. Затем я попытался сделать инструменты Android -> исправить проекты, но все же не повезло, я попытался изменить уровни в целях сборки. Я очистил его 100 раз, и все же он не работал. Тогда я решил удалить google-api-java-client-1.5.0-beta \ dependencies (jar-файлы, вызывающие ошибку), и затем он скомпилировался бы, но завис, потому что

11-02 20:44:27.093: WARN/System.err(485): java.lang.NoClassDefFoundError: com.google.gdata.client.books.BooksService

Мой код Android выглядит следующим образом:

import java.net.URL;

import com.google.gdata.client.books.BooksService;
import com.google.gdata.client.books.VolumeQuery;
import com.google.gdata.data.books.VolumeEntry;
import com.google.gdata.data.books.VolumeFeed;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidBooksApiActivity extends Activity {
Button btnSearch;
TextView tvTitle,tvISBN,tvAuthor,tvDatePublished;
EditText etSearch;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btnSearch=(Button)findViewById(R.id.btnFindBook);
    tvTitle=(TextView)findViewById(R.id.tvTitle);
    tvISBN=(TextView)findViewById(R.id.tvISBN);
    tvAuthor=(TextView)findViewById(R.id.tvAuthor);
    tvDatePublished=(TextView)findViewById(R.id.tvDatePublished);
    etSearch=(EditText)findViewById(R.id.etSearch);
    btnSearch.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try
            {   
                //String isbn;
                //isbn=etSearch.getText().toString();
                String isbn = "9780262140874";          

                BooksService booksService = new BooksService("UAH");        

                URL url = new URL("http://www.google.com/books/feeds/volumes/?q=ISBN%3C" + isbn + "%3E");

                VolumeQuery volumeQuery = new VolumeQuery(url);

                VolumeFeed volumeFeed = booksService.query(volumeQuery, VolumeFeed.class);

                VolumeEntry bookInfo=volumeFeed.getEntries().get(0);

                tvTitle.setText("Title: " + bookInfo.getTitles().get(0));
                tvISBN.setText("ISBN: " + isbn);
                tvAuthor.setText("Authors: " + bookInfo.getCreators());
                tvDatePublished.setText("DatePublished: "+bookInfo.getDates()+"\n");
            }catch(Throwable ex){tvTitle.setText(ex.getMessage()); ex.printStackTrace();}

          }
    });
}

}

Если у вас есть еще вопросы, я отвечу в меру своих возможностей. Я все еще учусь, поэтому возможно, что моя ошибка - это нечто простое, чего я просто не вижу.

    java.lang.IllegalArgumentException: already added:         Lcom/google/common/annotations/GwtCompatible;
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.processClass(Main.java:372)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.processFileBytes(Main.java:346)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.access$400(Main.java:59)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:294)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.processOne(Main.java:313)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.processAllFiles(Main.java:233)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.dx.command.dexer.Main.run(Main.java:185)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at java.lang.reflect.Method.invoke(Unknown Source)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(DexWrapper.java:179)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(BuildHelper.java:652)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(PostCompilerBuilder.java:510)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
[2011-11-03 14:25:51 - androidBooksApi] Dx  at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
[2011-11-03 14:25:53 - androidBooksApi] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.joda.time.DateTimeZone$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
[2011-11-03 14:25:57 - androidBooksApi] Dx 
trouble processing "javax/transaction/HeuristicCommitException.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2011-11-03 14:25:57 - androidBooksApi] Dx 2 errors; aborting
[2011-11-03 14:25:57 - androidBooksApi] Conversion to Dalvik format failed with error 1

Я попытался использовать команду deps из gdata-src.java-1.46.0.zip \ gdata \ java \ deps и снова, которая работала для java-приложения, но не для Android. Когда я использую папку deps в приложении для Android, он говорит, что

11-03 20:48:50.894: WARN/System.err(334): java.lang.NoClassDefFoundError: com.google.gdata.client.books.BooksService

Я знаю, что этого не может быть, потому что у java-приложения есть определение.

1 Ответ

0 голосов
/ 03 ноября 2011

Не могли бы вы настроить свои инструменты для запуска dx с флагом --debug? К сожалению, зная, что dx не удалось с Conversion to Dalvik format failed with error 1, недостаточно информации для решения проблемы. Если вы можете вставить полный вывод dx, у нас больше шансов выяснить, в чем дело.

...