Read from a sheet Google Sheets

0

I am developing an application on Android using Google Sheets as a database.

In my Google Sheets sheet I have information stored about books (author, title, date, etc), and I want to recover it and paint it in a ListView . On the one hand, I have created a BookItem object, and on the other hand I have an adapter BookAdapter . Then, in Spreadsheets.java , is where I have the method that reads the sheet, called getDataFromApi() , which works, but I do not know how to adapt it to my BookAdapter and that I paint the list.

Then I leave the code that I commented:

  • BookItem
public class BookItem {
    static String title_item;
    static Drawable cover_item; //probar con String

    public BookItem(String title, Drawable cover){
        super();
        this.title_item = title;
        this.cover_item = cover;
    }

    public String getTitle() {
        return title_item;
    }

    public void setTitle(String title){
        this.title_item = title;
    }

    public static Drawable getCover() {
        return cover_item;
    }

    public void setCover(Drawable cover) {
        this.cover_item = cover;
    }
  • BookAdapter
public class BookAdapter extends BaseAdapter {

   //private ArrayList<BookItem> items;
    List<BookItem> items;
    private Context context;

    public BookAdapter (Context context, List<BookItem> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public BookItem getItem(int position) {
        return this.items.get(position);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    private static class ViewHolder {
        public final ImageView cover_item;
        public final TextView title_item;

        public ViewHolder (ImageView cover_item, TextView title_item){
            this.cover_item = cover_item;
            this.title_item = title_item;
        }
    }

    @Override
    public View getView (int position, View view, ViewGroup viewGroup) {
        ImageView cover_item;
        TextView title_item;

        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
            title_item = (TextView) view.findViewById(R.id.book_title_item);
            cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
            view.setTag(R.id.book_title_item, title_item);
            view.setTag(R.id.book_cover_item, cover_item);
        }
        else {
            cover_item = (ImageView) view.getTag(R.id.book_cover_item);
            title_item = (TextView)view.getTag(R.id.book_title_item);
        }
        BookItem bookItem = getItem(position);
        cover_item.setImageDrawable(bookItem.getCover());
        title_item.setText(bookItem.getTitle());

        return view;
    }

}
  • Spreadsheets
public class Spreadsheets extends Activity {

    static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
    static String read_only = "no";
    static String book_favorite = "no";
    static GoogleAccountCredential mCredential;
    private ListView bookList;
    private TextView mOutputText;
    ProgressDialog mProgress;
    Context context;
    List<String> rst;
    List<BookItem> resultados;
    BookAdapter adapter;

    private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.spread);

        // mOutputText = (TextView) findViewById(R.id.outputText);
       bookList = (ListView) findViewById(R.id.bookList);
        //  mOutputText.setText("");

        mProgress = new ProgressDialog(this);
        mProgress.setMessage("Calling Google Sheets...");

        // Initialize credentials and service object.
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

        System.out.print("read only es igual a "+ read_only);
        new MakeRequestTask(mCredential).execute();
    }

    public void rellenar(){
        System.out.println("VOY A HACER NEW BOOK ADAPTER ");
        adapter = new BookAdapter(context, resultados);
        bookList.setAdapter(adapter);
        System.out.println("SETADAPTER");
    }

    private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private Exception mLastError = null;
        MakeRequestTask(GoogleAccountCredential credential) {
        }

        @Override
        protected List<String> doInBackground(Void... params) {
            try {
                if(read_only.equals("no")) {
                    setDataToApi();
                    return null;
                }
                else {
                    return getDataFromApi();
                }
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        private List<String> getDataFromApi() throws IOException {

            String range = "Sheet1!A1:H";
            List<String> results = new ArrayList<String>();
            ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
                    .get(CreateSpreadsheets.spreadsheet_id, range)
                    .execute();
            List<List<Object>> values = response.getValues();
            if (values != null) {
                for (List row : values) {
                    results.add(row.get(0) + ", " + row.get(7));
                }
            }
            //funcion();
            return results;
        }

        private void setDataToApi() throws IOException {

            String range = "Sheet1!A2:H";
            List<List<Object>> values = new ArrayList<>();

            List<Object> data1 = new ArrayList<>();

            data1.add(book_title);
            data1.add(book_author);
            data1.add(book_date);
            data1.add(book_category);
            data1.add(book_description);
            data1.add(book_rating);
            data1.add(book_cover);
            data1.add("a");

            values.add(data1);
            ValueRange valueRange = new ValueRange();
            valueRange.setMajorDimension("ROWS");
            valueRange.setRange(range);
            valueRange.setValues(values);

            ValueRange body = new ValueRange().setValues(values);

            AppendValuesResponse response =
                    CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
                            .setValueInputOption("RAW")
                            .execute();
        }

        @Override
        protected void onPreExecute() {
            //mOutputText.setText("");
            mProgress.show();
        }

        @Override
        protected void onPostExecute(List<String> output) {
            mProgress.hide();
            if (output == null || output.size() == 0) {
                //   mOutputText.setText("No results returned.");
            } else {
                if(read_only.equals("no")) {
                    Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
                    startActivity(intent);
                    //  mOutputText.setText("Se ha añadido un libro a su lista");
                }
                else {
                    System.out.println("VOY A RELLENAR LA LISTA");
                    rellenar();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }

    }

My application has a NavigationDrawer, and from the "My Bookshelf" option I call "Spredsheets" to load in ListView. I leave my MainActivity below:

import static com.example.apptfg.CreateSpreadsheets.first_time_spread;
import static com.example.apptfg.Spreadsheets.read_only;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private Toolbar toolbar;
Button scan_button, ok_button;
static String ean_content, title;

static String first_time = "si";
private SharedPreferences preferences = null;
int mode = Context.MODE_PRIVATE;

ImageView image_user;

String username, user_email;
TextView info_text, user, email;
View divider, header;
EditText name_input, email_input;
CheckBox remember_check;

static final int REQUEST_IMAGE_CAPTURE = 1;
static Uri mLocationForPhotos;

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

    toolbar.setTitleTextColor(getResources().getColor(R.color.colorLetras));
    getSupportActionBar().setTitle("Mi Estanteria");

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    header = navigationView.getHeaderView(0);

    image_user = (ImageView)header.findViewById(R.id.image_user);
    image_user.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.image_user:
                    captureImage();
                    break;
         }
        }
    });

    scan_button = (Button) findViewById(R.id.scan_button);

    //userSignIn();
    firstTime();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

public void captureImage () {
    Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(Intent.createChooser(gallery, "Selecciona una imagen de perfil"), REQUEST_IMAGE_CAPTURE);
}

 public void firstTime(){

        if (preferences.getBoolean("hil", true)) {
            System.out.println("Entro en first time");
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle(R.string.title_firsttime);
            dialog.setMessage(R.string.message_firsttime);
            dialog.setPositiveButton("Sí", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    first_time_spread = first_time.toString();
                    Intent intent = new Intent(MainActivity.this, CreateSpreadsheets.class);
                    intent.putExtra(first_time_spread, first_time_spread);
                    startActivity(intent);
                }
            });
            dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
            dialog.show();
            preferences.edit().putBoolean("hil", false).apply();
        }
    }

public void userSignIn() {

    AlertDialog.Builder ad1 = new AlertDialog.Builder(this);
    setContentView(R.layout.user_login);


    info_text = (TextView)findViewById(R.id.info_text);
    divider = findViewById(R.id.divider);
    name_input = (EditText) findViewById(R.id.name_input);
    email_input = (EditText) findViewById(R.id.email_input);
    remember_check = (CheckBox) findViewById(R.id.remember_check);
    ok_button = (Button) findViewById(R.id.ok_button);
    ad1.setTitle(R.string.info_text);

    ok_button.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    username = name_input.getText().toString();
                    user_email = email_input.getText().toString();

                    preferences = getSharedPreferences("preferences", mode);
                    preferences.edit().putString("user", username).apply();
                    preferences.edit().putString("email", user_email).apply();

                    user = (TextView) header.findViewById(R.id.user);
                    email = (TextView) header.findViewById(R.id.email);

                    firstTime();
                }
            }
    );
    ad1.show();
}

public void scanBarcode(View view) {
    try {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        startActivityForResult(intent, 0);
    } catch (ActivityNotFoundException e) {
        showDialog(MainActivity.this, "No se ha encontrado Barcode Scanner", "¿Descargar Barcode Scanner?", "Sí", "No").show();
    }
}

private Dialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence yes, CharSequence no) {

    AlertDialog.Builder download = new AlertDialog.Builder(act);
    download.setTitle(title);
    download.setMessage(message);
    download.setPositiveButton(yes, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent data = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(data);
            } catch (ActivityNotFoundException e) {
            }
        }
    });
    download.setNegativeButton(no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
        }
    });
    return download.show();
}

@Override
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();
    Fragment fragment = null;
    boolean FragmentTransaction = false;

    if (id == R.id.Mi_estanteria) {
        Intent intent = new Intent (MainActivity.this, Spreadsheets.class);
        intent.putExtra(read_only,"si");
        startActivity(intent);
        /*getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.drawer_layout, MiEstanteria.newInstance(), MiEstanteria.TAG)
                .commit();*/
       // fragment = new MiEstanteria();
        //getSupportFragmentManager().findFragmentById(android.R.id.list);
        //FragmentTransaction = true;

    }  else if (id == R.id.Escanear) {
        View view = null;
        fragment = new Escanear();
        FragmentTransaction = true;
        scanBarcode(view);

    } else if (id == R.id.nav_share) {


    } else if (id == R.id.nav_send) {

    }

    if (FragmentTransaction) {
        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragment).commit();
        item.setChecked(true);
        getSupportActionBar().setTitle(item.getTitle());
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


public static class Escanear extends Fragment {

    public Escanear() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_escanear, container, false);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK && requestCode == REQUEST_IMAGE_CAPTURE){
        mLocationForPhotos = data.getData();
        image_user.setImageURI(mLocationForPhotos);
    }

    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = data.getStringExtra("SCAN_RESULT");
            String format = data.getStringExtra("SCAN_RESULT_FORMAT");
            if (format.equals("EAN_13")) {
                ean_content = contents;
                Intent intent = new Intent(MainActivity.this, GetBookInfo.class);
                intent.putExtra(ean_content, ean_content);
                startActivity(intent);
            } else {
                Toast toast = Toast.makeText(this, "El formato debe ser EAN_13", Toast.LENGTH_LONG);
                toast.show();
            }
        } else if (resultCode == RESULT_CANCELED) {
            Toast toast2 = Toast.makeText(this, "Ha ocurrido un error escaneando", Toast.LENGTH_LONG);
            toast2.show();
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem item = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) item.getActionView();
    searchView.setQueryHint("Buscar");
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            //Se activa cuando se pulsa "Buscar"
            Intent intent1 = new Intent(MainActivity.this, GetBookInfo.class);
            title = query.replaceAll(" ", "%20");
            intent1.putExtra(title, title);
            System.out.println("El titulo es"+title);
            startActivity(intent1);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            //Se activa cuando se escribe un unico caracter
            return false;
        }
    });
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.settings:
            Intent intent2 = new Intent(MainActivity.this, Ajustes.class);
            startActivity(intent2);
            return true;
        case R.id.about:
            Intent intent3 = new Intent(MainActivity.this, About.class);
            startActivity(intent3);
            return true;
        case R.id.exit:
            new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Salir")
                    .setMessage("¿Estás seguro?").setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

}

The xml " spread " that is inflated in Activity Spreadsheest is simply a list, and the xml " fila_lista_miestanteria " consists of a TextView and a ImageView to show the info of each one of the books.

Thank you very much in advance.

    
asked by A_mmaa_ 21.01.2018 в 22:05
source

1 answer

0

As I'm not clear about the images, I'll only do it with the text you get from the spreadsheet.

@Override
protected void onPostExecute(List<String> output) {
    mProgress.hide();
    if (output == null || output.size() == 0) {
        // mOutputText.setText("No results returned.");
    } else {
        if(read_only.equals("no")) {
            Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
            startActivity(intent);
            // mOutputText.setText("Se ha añadido un libro a su lista");
        }
        else {
            System.out.println("VOY A RELLENAR LA LISTA");

            // Agregas los resultado obtenidos de la hoja de calculo
            // a la lista resultados que es la que pasas al adaptador.
            resultados = new ArrayList<>();
            for(String resultado : output) {
                resultados.add(new BookItem(resultado, null));
            }

            rellenar();
        }
    }
}

With those few lines of code that add your ListView should work.

    
answered by 22.01.2018 / 02:35
source