@Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Using SQLiteQueryBuilder to create a query
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    // Check if the caller has requested a column which does not exist
    checkColumns(projection);

    // Set the table
    queryBuilder.setTables(NOTE_TABLE);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ALL_NOTES:
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor =
        queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);

    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
  }
 @Override
 public void open() throws SQLException {
   if (database != null) {
     if (database.isOpen()) database.close();
   }
   database = dbHelper.getWritableDatabase();
 }
  public Livro getLivro(int id) {

    // 1. get reference to readable DB
    Livro livro = new Livro();
    SQLiteMaterial dbMaterial = new SQLiteMaterial(con);
    SQLiteDatabase db = banco.getReadableDatabase();

    // 2. build query
    Cursor cursor =
        db.query(
            TABLE_LIVRO, // a. table
            COLUMNS, // b. column names
            " id = ?", // c. selections
            new String[] {String.valueOf(id)}, // d. selections args
            null, // e. group by
            null, // f. having
            null, // g. order by
            null); // h. limit

    // 3. if we got results get the first one
    if (cursor != null) cursor.moveToFirst();

    idLivro = cursor.getColumnIndex(KEY_ID);
    autor = cursor.getColumnIndex(KEY_AUTOR);
    cutter = cursor.getColumnIndex(KEY_CUTTER);
    isbn = cursor.getColumnIndex(KEY_ISBN);
    numeroTombo = cursor.getColumnIndex(KEY_NUMERO_TOMBO);

    idMaterial = cursor.getColumnIndex(sqlLiteMaterial.KEY_ID);
    ano = cursor.getColumnIndex(sqlLiteMaterial.KEY_ANO);
    classificacao = cursor.getColumnIndex(sqlLiteMaterial.KEY_CLASSIFICACAO);
    editora = cursor.getColumnIndex(sqlLiteMaterial.KEY_EDITORA);
    local = cursor.getColumnIndex(sqlLiteMaterial.KEY_LOCAL);
    referencia = cursor.getColumnIndex(sqlLiteMaterial.KEY_REFERENCIA);
    titulo = cursor.getColumnIndex(sqlLiteMaterial.KEY_TITULO);
    unitermo = cursor.getColumnIndex(sqlLiteMaterial.KEY_UNITERMO);
    volume = cursor.getColumnIndex(sqlLiteMaterial.KEY_VOLUME);

    // 4. tabela material
    livro = new Livro();
    livro.setCodigoMaterial(Integer.parseInt(cursor.getString(idMaterial)));
    livro.setAno(cursor.getString(ano));
    livro.setClassificacao(cursor.getString(classificacao));
    livro.setEditora(cursor.getString(editora));
    livro.setLocal(cursor.getString(local));
    livro.setReferencia(cursor.getString(referencia));
    livro.setTitulo(cursor.getString(titulo));
    livro.setUnitermo(cursor.getString(unitermo));
    livro.setVolume(cursor.getString(volume));

    livro.setCodigoLivro(Integer.parseInt(cursor.getString(idLivro)));
    livro.setAutor(cursor.getString(autor));
    livro.setCutter(cursor.getString(cutter));
    livro.setIsbn(cursor.getString(isbn));
    livro.setNumeroTombo(cursor.getString(numeroTombo));

    Log.d("getLivro(" + id + ")", livro.toString());
    return livro;
  }
  public ArrayList<Livro> getAllLivro() {

    ArrayList<Livro> listaLivros = new ArrayList<Livro>();
    SQLiteMaterial sqlMaterial; // = new SQLiteMaterial(con);
    // 1. build the query//

    String query = SQL_SELECT + SQL_GROUP_BY;

    // 2. get reference to writable DB
    SQLiteDatabase db = banco.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    Livro livro = null;
    if (cursor.moveToFirst()) {
      do {

        livro = new Livro();
        idLivro = cursor.getColumnIndex(KEY_ID);
        autor = cursor.getColumnIndex(KEY_AUTOR);
        cutter = cursor.getColumnIndex(KEY_CUTTER);
        isbn = cursor.getColumnIndex(KEY_ISBN);
        numeroTombo = cursor.getColumnIndex(KEY_NUMERO_TOMBO);

        idMaterial = cursor.getColumnIndex(sqlLiteMaterial.KEY_ID);
        ano = cursor.getColumnIndex(sqlLiteMaterial.KEY_ANO);
        classificacao = cursor.getColumnIndex(sqlLiteMaterial.KEY_CLASSIFICACAO);
        editora = cursor.getColumnIndex(sqlLiteMaterial.KEY_EDITORA);
        local = cursor.getColumnIndex(sqlLiteMaterial.KEY_LOCAL);
        referencia = cursor.getColumnIndex(sqlLiteMaterial.KEY_REFERENCIA);
        titulo = cursor.getColumnIndex(sqlLiteMaterial.KEY_TITULO);
        unitermo = cursor.getColumnIndex(sqlLiteMaterial.KEY_UNITERMO);
        volume = cursor.getColumnIndex(sqlLiteMaterial.KEY_VOLUME);

        // 4. tabela material
        livro.setCodigoMaterial(Integer.parseInt(cursor.getString(idMaterial)));
        livro.setAno(cursor.getString(ano));
        livro.setClassificacao(cursor.getString(classificacao));
        livro.setEditora(cursor.getString(editora));
        livro.setLocal(cursor.getString(local));
        livro.setReferencia(cursor.getString(referencia));
        livro.setTitulo(cursor.getString(titulo));
        livro.setUnitermo(cursor.getString(unitermo));
        livro.setVolume(cursor.getString(volume));

        livro.setCodigoLivro(Integer.parseInt(cursor.getString(idLivro)));
        livro.setAutor(cursor.getString(autor));
        livro.setCutter(cursor.getString(cutter));
        livro.setIsbn(cursor.getString(isbn));
        livro.setNumeroTombo(cursor.getString(numeroTombo));

        listaLivros.add(livro);
      } while (cursor.moveToNext());
    }

    Log.d("getAllLivro()", listaLivros.toString());
    return listaLivros;
  }
  public void reiniciaTabelaMensagem(SQLiteDatabase db) {

    String DELETE_TABLE = "DELETE FROM livro";
    String DELETE_INDEX_TABLE = " DELETE FROM SQLITE_SEQUENCE WHERE NAME = 'livro'";

    db.execSQL(DELETE_TABLE);
    db.execSQL(DELETE_INDEX_TABLE);
    banco.onCreate(db);
  }
  public void editMovie(int mID, String mTitle) {
    LinearLayout viewGroup = (LinearLayout) findViewById(R.id.popupLinearLayout);
    LayoutInflater layoutInflater =
        (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    editMovieLayout = layoutInflater.inflate(R.layout.edit_movie, viewGroup);

    selectedMovie = db.getMovie(mID);

    int popupDimensions = WindowManager.LayoutParams.MATCH_PARENT;

    TextView mName = (TextView) editMovieLayout.findViewById(R.id.editMovieName);
    mName.setText(mTitle);

    final RatingBar mRating = (RatingBar) editMovieLayout.findViewById(R.id.editRating);
    mRating.setRating(selectedMovie.getRating());

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow();
    popup.setContentView(editMovieLayout);
    popup.setWidth(popupDimensions);
    popup.setHeight(popupDimensions);
    popup.setFocusable(true);
    // popup.setAnimationStyle(R.style.PopupWindowAnimation);

    // Displaying the popup at the specified location, + offsets.
    popup.showAtLocation(editMovieLayout, Gravity.CENTER, 0, 0);

    ImageButton close = (ImageButton) editMovieLayout.findViewById(R.id.close);
    close.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            popup.dismiss();
          }
        });

    Button save = (Button) editMovieLayout.findViewById(R.id.saveMovieButton);
    save.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            selectedMovie.setRating(mRating.getRating());
            db.updateMovie(selectedMovie);
            try {
              populateMyMovies(lv);
            } catch (ParseException e) {
              e.printStackTrace();
            }
            popup.dismiss();
          }
        });
  }
  @Override
  public List<Event> getAllEntries() {
    List<Event> events = new ArrayList<Event>();

    String[] allColumnNames = dbHelper.getAllColumnNames(MySQLiteHelper.TABLE_EVENTS);

    if (database == null) database = dbHelper.getReadableDatabase();

    Cursor cursor =
        database.query(MySQLiteHelper.TABLE_EVENTS, allColumnNames, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Event event = cursorToEvent(cursor);
      events.add(event);
      cursor.moveToNext();
    }

    // Make sure to close the cursor
    cursor.close();
    return events;
  }
  @Override
  public Object createEntry(String data) {

    ContentValues values = new ContentValues();

    int endTitle = data.indexOf(";");
    int endUser = data.indexOf(";", endTitle + 1);
    int endStartTime = data.indexOf(";", endUser + 1);
    int endEndTime = data.indexOf(";", endStartTime + 1);
    int endDescription = data.indexOf(";", endEndTime + 1);

    String title = data.substring(0, endTitle);
    String user = data.substring(endTitle + 1, endUser);
    Long starttime = Long.getLong(data.substring(endUser + 1, endStartTime));
    Long endtime = Long.getLong(data.substring(endStartTime + 1, endEndTime));
    String description = (data.substring(endEndTime + 1, endDescription));
    String profilePicURI = (data.substring(endDescription + 1, data.length()));

    // TODO start and endtime check
    starttime = System.currentTimeMillis();
    endtime = System.currentTimeMillis();
    if (";".equals(profilePicURI)) profilePicURI = "";

    values.put(MySQLiteHelper.COLUMN_TIMESTAMP, System.currentTimeMillis());
    values.put(MySQLiteHelper.COLUMN_TITLE, title);
    values.put(MySQLiteHelper.COLUMN_USERNAME, user);
    values.put(MySQLiteHelper.COLUMN_STARTTIME, starttime);
    values.put(MySQLiteHelper.COLUMN_ENDTIME, endtime);
    values.put(MySQLiteHelper.COLUMN_DESCRIPTION, description);
    values.put(MySQLiteHelper.COLUMN_PICPROFILEURI, profilePicURI);

    long insertId = database.insert(MySQLiteHelper.TABLE_EVENTS, null, values);

    String[] allColumnNames = dbHelper.getAllColumnNames(MySQLiteHelper.TABLE_EVENTS);
    Cursor cursor =
        database.query(
            MySQLiteHelper.TABLE_EVENTS,
            allColumnNames,
            MySQLiteHelper.COLUMN_ID + " = " + insertId,
            null,
            null,
            null,
            null);

    Event event = null;
    if (cursor.moveToFirst()) event = cursorToEvent(cursor);
    cursor.close();
    return event;
  }
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
   // TODO Auto-generated method stub
   int uriType = sURIMatcher.match(uri);
   switch (uriType) {
     case ALL_NOTES:
       break;
     default:
       throw new IllegalArgumentException("Unknown URI: " + uri);
   }
   SQLiteDatabase db = database.getWritableDatabase();
   int numDeleted = db.delete(MySQLiteHelper.TABLE_COMMENTS, selection, null);
   Log.w(MainActivity.TAG, "Deleted items: " + String.valueOf(numDeleted));
   return numDeleted;
 }
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    Date date = new Date();
    values.put(MySQLiteHelper.COLUMN_DATE_MODIFIED, date.getTime());
    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ALL_NOTES:
        break;

      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    SQLiteDatabase db = database.getWritableDatabase();

    int numRows = db.update(MySQLiteHelper.TABLE_COMMENTS, values, selection, null);
    return numRows;
  }
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    // Check what we are inserting
    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case NOTE_ID:
        values.put(MySQLiteHelper.COLUMN_CONTENTS, "");
        values.put(MySQLiteHelper.COLUMN_DATE_MODIFIED, new Date().getTime());
        SQLiteDatabase db = database.getWritableDatabase();
        long id = db.insert(MySQLiteHelper.TABLE_COMMENTS, null, values);
        Uri returnUri = Uri.parse(uri + "/" + String.valueOf(id));

        return returnUri;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
  }
  public long addLivro(Livro livro) {
    Log.d("addLivro", livro.getClassificacao());
    // 1. get reference to writable DB

    SQLiteMaterial dbMaterial = new SQLiteMaterial(con);
    SQLiteDatabase db = banco.getWritableDatabase();
    ContentValues values = new ContentValues();
    Material material = new Material();
    long i = 0;

    material.setAno(livro.getAno());
    material.setClassificacao(livro.getClassificacao());
    material.setEditora(livro.getEditora());
    material.setLocal(livro.getLocal());
    material.setReferencia(livro.getReferencia());
    material.setTitulo(livro.getTitulo());
    material.setUnitermo(livro.getUnitermo());
    material.setVolume(livro.getVolume());

    if (dbMaterial.addMaterial(material) > 0) {

      material = new Material();
      material = dbMaterial.getUltimoMaterial();
      if (material.getCodigoMaterial() > 0) {

        values.put(KEY_ID_MATERIAL, material.getCodigoMaterial());
        values.put(KEY_AUTOR, livro.getAutor());
        values.put(KEY_CUTTER, livro.getCutter());
        values.put(KEY_ISBN, livro.getIsbn());
        values.put(KEY_NUMERO_TOMBO, livro.getNumeroTombo());

        // 3. insert
        i =
            db.insert(
                TABLE_LIVRO, // table
                null, // nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
      }
    }
    return i;
  }
  @Override
  public boolean validarFecha(int dia, int mes, int anio, boolean bool) {
    // creo el calendario que me dara el timestamp en milisegundos

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, dia);
    cal.set(Calendar.MONTH, mes);
    cal.set(Calendar.YEAR, anio);
    mes = mes + 1;

    // a partir del calendario puesto en fecha obtengo los milisegundos
    long t = cal.getTimeInMillis(); // + (1000 * 60 * 60 * 24 * 7 * 4);
    long current = new Date().getTime();
    long dif = current - t;
    Integer mili_week = 604800000;
    Long week = dif / mili_week;
    ++week;
    Log.d("sqle", "" + dif + " / " + mili_week + " = " + week);

    Date aux = new Date(t);
    Log.d("sqle", aux.toString());

    if (t <= current /*|| week == 0*/) {
      // guardo el texto con la fecha y la calculo
      try {

        String fecha = " " + dia + "-" + mes + "-" + anio;
        String timestamp = "" + t;
        String week_str = "" + week;
        Log.d("sqle", "fecha " + fecha);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("fecha_str", fecha);
        map.put("fecha_t", timestamp);
        map.put("fecha_en_semanas", week_str);

        MySQLiteHelper db = new MySQLiteHelper(this);
        if (bool) {
          db.updateFechaPeriodo(map);
          bool = true;
        } else {
          if (db.agregarFechas(map)) {
            bool = true;

          } else {
            bool = false;
          }
        }

      } catch (Exception e) {
        Toast.makeText(
                PanzaGaleria.this,
                "No se pudo guardar la fecha. Se le requerira en algunas secciones.",
                Toast.LENGTH_LONG)
            .show();
        bool = false;
      }

    } else {
      // lanzo un error y le digo que ponga bien la fecha
      Toast.makeText(PanzaGaleria.this, "Fecha no valida", Toast.LENGTH_SHORT).show();
      this.ingresarFecha();
      bool = false;
    }
    return bool;
  }
 @Override
 public void close() {
   dbHelper.close();
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ClassScoreboard userScore;
    ClassUser user;
    MySQLiteHelper db;
    ClassLevel userLevel;

    ProgressBar mProgress;

    int circleAvatarV, pointsUV, answeredWrongUV, questionsA;
    String levelNameV, levelDiscripV, usernameUV, emailUV, levelUV;

    View view = inflater.inflate(R.layout.fragment_userdetails, container, false);
    user = getArguments().getParcelable("chosenUser");
    db = new MySQLiteHelper(getActivity());
    userScore = db.getScore(user.getUser_id());
    userLevel = db.getLevel(userScore.getLevel_id());

    ImageView circleAvatar = (ImageView) view.findViewById(R.id.circleAvatar);
    TextView levelName = (TextView) view.findViewById(R.id.levelName);
    TextView levelDiscrip = (TextView) view.findViewById(R.id.levelDiscrip);
    TextView usernameU = (TextView) view.findViewById(R.id.usernameU);
    TextView emailU = (TextView) view.findViewById(R.id.emailU);
    TextView pointsU = (TextView) view.findViewById(R.id.pointsU);
    TextView levelU = (TextView) view.findViewById(R.id.levelU);
    TextView answeredWrongU = (TextView) view.findViewById(R.id.answeredWrongU);
    TextView answeredQuestions = (TextView) view.findViewById(R.id.answeredQuestionsU);

    circleAvatarV =
        getResources()
            .getIdentifier(
                user.getAvatar().toLowerCase(Locale.getDefault()),
                "drawable",
                getActivity().getPackageName());
    circleAvatar.setImageResource(circleAvatarV);

    levelNameV = userLevel.getLevelname();
    levelName.setText(levelNameV);

    levelDiscripV = userLevel.getLevelname();
    levelDiscrip.setText(levelDiscripV);

    usernameUV = user.getUsername();
    usernameU.setText(usernameUV);

    emailUV = user.getEmail();
    emailU.setText(emailUV);

    pointsUV = userScore.getPoints();
    pointsU.setText((String.valueOf(pointsUV)));

    answeredWrongUV = userScore.getWrong_number();
    answeredWrongU.setText((String.valueOf(answeredWrongUV)));

    levelUV = Integer.toString(userScore.getLevel_id());
    levelU.setText(levelUV);

    questionsA = (pointsUV / 10) + answeredWrongUV;
    answeredQuestions.setText(String.valueOf(questionsA));

    mProgress = (ProgressBar) view.findViewById(R.id.progressBarU);
    mProgress.setProgress(pointsUV);

    ImageView btn;
    TextView txtV;
    for (int i = 1; i <= userScore.getLevel_id(); i++) {
      if (pointsUV >= i * 50) {
        if (i == 1) {
          txtV = (TextView) view.findViewById(R.id.txvElements);
          txtV.setVisibility(View.VISIBLE);
        }
        if (i == 9) {
          txtV = (TextView) view.findViewById(R.id.txvchallenges);
          txtV.setVisibility(View.VISIBLE);
        }
        btn =
            (ImageView)
                view.findViewById(
                    getResources()
                        .getIdentifier(
                            "imageView" + String.valueOf(i), "id", getActivity().getPackageName()));
        btn.setVisibility(View.VISIBLE);
      }
    }

    return view;
  }
  protected void onCreate(Bundle savedInstanceState) {

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_medicine);

    mySQLiteHelper = new MySQLiteHelper(add_medicine.this, "notepad.db", null, 1);
    db = mySQLiteHelper.getReadableDatabase();
    text21m = (EditText) findViewById(R.id.text21m);
    latest_medicine = (TextView) findViewById(R.id.latest_medicine);
    latest_mdcount = (TextView) findViewById(R.id.latest_mdcount);
    latest_time = (TextView) findViewById(R.id.latest_truetime);
    input_count = (EditText) findViewById(R.id.input_count);
    medicine_name = (EditText) findViewById(R.id.medicine_name);

    TabHost tabHost;
    tabHost = getTabHost();
    tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("录入").setContent(R.id.text1m));
    tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("笔记").setContent(R.id.text2m));
    tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("日志").setContent(R.id.text3m));

    tabHost.setCurrentTab(0);

    // 用SharedPreference储存note
    SharedPreferences sp1 = getSharedPreferences("mdnote", MODE_PRIVATE);
    String notesString = sp1.getString("mdnote", "");
    text21m.setText(notesString);

    cursor =
        db.query(
            "medicinetable",
            new String[] {"_id", "md", "mdcount", "time"},
            null,
            null,
            null,
            null,
            null);

    if (cursor.moveToNext() != true) {
      latest_medicine.setText("");
      latest_time.setText("");
      latest_mdcount.setText("");
      // cursor.close();
    } else {

      cursor.moveToLast();
      int mdindex = cursor.getColumnIndex("md");
      String md = cursor.getString(mdindex);
      int mdcountindex = cursor.getColumnIndex("mdcount");
      String mdcount = cursor.getString(mdcountindex);
      int timeindex = cursor.getColumnIndex("time");
      String date = cursor.getString(timeindex);
      latest_medicine.setText(md);
      latest_time.setText(date);
      latest_mdcount.setText(mdcount);
      // cursor.close();

    }

    tv = (TextView) findViewById(R.id.TextView001m);
    lv = (ListView) findViewById(R.id.ListView01m);
    // 数据库
    // db=mySQLiteHelper.getReadableDatabase();
    // cursor=db.query("medicinetable", new String[]{"_id","md","mdcount","time"}, null, null, null,
    // null, null);

    if (cursor.getCount() > 0) {
      tv.setVisibility(View.GONE);
    }

    SimpleCursorAdapter sca =
        new SimpleCursorAdapter(
            add_medicine.this,
            R.layout.md_item,
            cursor,
            new String[] {"md", "mdcount", "time"},
            new int[] {R.id.TextView01m, R.id.TextView02m, R.id.TextView03m});
    lv.setAdapter(sca);

    lv.setOnItemClickListener(
        new OnItemClickListener() {

          public void onItemClick(AdapterView<?> arg0, View arg1, int which, long arg3) {

            Builder builder = new Builder(add_medicine.this);
            builder.setSingleChoiceItems(
                new String[] {"查看", "修改", "删除"},
                -1,
                new OnClickListener() {

                  public void onClick(DialogInterface dialog, int which) {

                    if (which == 0 && cursor.getCount() != 0) {
                      int mdindex = cursor.getColumnIndex("md");
                      mdString = cursor.getString(mdindex);
                      int ctindex = cursor.getColumnIndex("mdcount");
                      ctString = cursor.getString(ctindex);

                      Toast.makeText(
                              add_medicine.this,
                              mdString + "|" + ctString + "片",
                              Toast.LENGTH_SHORT)
                          .show();
                    } else if (which == 2 && cursor.getCount() != 0) {

                      int myidindex = cursor.getColumnIndex("_id");
                      myid = cursor.getInt(myidindex);
                      Builder builder02 = new Builder(add_medicine.this);
                      LayoutInflater inflater = LayoutInflater.from(add_medicine.this);
                      View view = inflater.inflate(R.layout.deleteview, null);
                      builder02.setView(view);
                      builder02.setPositiveButton(
                          "确定",
                          new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                              db.delete("medicinetable", "_id=" + myid, null);
                              cursor =
                                  db.query(
                                      "medicinetable",
                                      new String[] {"_id", "md", "mdcount", "time"},
                                      null,
                                      null,
                                      null,
                                      null,
                                      null);

                              SimpleCursorAdapter sca =
                                  new SimpleCursorAdapter(
                                      add_medicine.this,
                                      R.layout.md_item,
                                      cursor,
                                      new String[] {"md", "mdcount", "time"},
                                      new int[] {
                                        R.id.TextView01m, R.id.TextView02m, R.id.TextView03m
                                      });
                              lv.setAdapter(sca);
                            }
                          });
                      builder02.setNegativeButton(
                          "取消",
                          new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {}
                          });
                      builder02.show();
                    } else if (which == 1 && cursor.getCount() != 0) {
                      // 取得数据
                      int myidindex = cursor.getColumnIndex("_id");
                      myid = cursor.getInt(myidindex);
                      Builder builder01 = new Builder(add_medicine.this);

                      builder01.setTitle("编辑");

                      LayoutInflater inflater = LayoutInflater.from(add_medicine.this);
                      View view = inflater.inflate(R.layout.md_updatedialogview, null);
                      et01 = (EditText) view.findViewById(R.id.ed1m);
                      et02 = (EditText) view.findViewById(R.id.ed2m);
                      builder01.setView(view);
                      builder01.setPositiveButton(
                          "确定",
                          new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {

                              String md = et01.getText().toString();
                              String ct = et02.getText().toString();

                              if (TextUtils.isEmpty(md) || TextUtils.isEmpty(ct)) {

                              } else {
                                ContentValues cv = new ContentValues();
                                cv.put("md", md);
                                cv.put("mdcount", ct);

                                db.update("medicinetable", cv, "_id=" + myid, null);
                                cursor =
                                    db.query(
                                        "medicinetable",
                                        new String[] {"_id", "md", "mdcount", "time"},
                                        null,
                                        null,
                                        null,
                                        null,
                                        null);

                                SimpleCursorAdapter sca =
                                    new SimpleCursorAdapter(
                                        add_medicine.this,
                                        R.layout.md_item,
                                        cursor,
                                        new String[] {"md", "mdcount", "time"},
                                        new int[] {
                                          R.id.TextView01m, R.id.TextView02m, R.id.TextView03m
                                        });
                                lv.setAdapter(sca);
                              }
                            }
                          });
                      builder01.setNegativeButton(
                          "取消",
                          new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {}
                          });
                      builder01.show();
                    }
                  }
                });
            builder.show();
          }
        });
  }
Exemple #17
0
 public NoteDataSource(Context context) {
   sqlHelper = MySQLiteHelper.getsInstance(context);
   this.database = sqlHelper.getWritableDatabase();
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_search_list);
    list = getListView();
    backBtn = (ImageButton) findViewById(R.id.backBtn);
    priceBtn = (Button) findViewById(R.id.orderByPriceBtn);
    timeBtn = (Button) findViewById(R.id.orderByTimeBtn);
    tvnomatchfound = (TextView) findViewById(R.id.tvnomatchfound);
    backBtn.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View arg0) {
            // TODO Auto-generated method stub

            new HomeFragment().refresh();

            shared.fromString = "";
            shared.toString = "";
            shared.through1String = "";
            shared.fromPrice = "";
            shared.toPrice = "";
            shared.departureDate = "";
            shared.day = "";
            if (shared.through2String.length() > 0) {
              shared.through2String = "";
            }
            if (shared.through3String.length() > 0) {
              shared.through3String = "";
            }

            if (HomeFragment.throughPath2 != null) {
              HomeFragment.throughPath2.setText("");
              HomeFragment.throughPath2.setEnabled(true);
              HomeFragment.throughPath2.setFocusableInTouchMode(true);
              HomeFragment.throughPath2.setError(null);
            }
            if (HomeFragment.throughPath3 != null) {
              HomeFragment.throughPath3.setText("");
              HomeFragment.throughPath3.setEnabled(true);
              HomeFragment.throughPath3.setFocusableInTouchMode(true);
              HomeFragment.throughPath3.setError(null);
            }

            HomeActivity.mFrameLayout.setVisibility(View.GONE);
            finish();
          }
        });

    priceBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            // TODO Auto-generated method stub
            @SuppressWarnings("unused")
            String arrange = selectQuery("cost", true);

            Toast.makeText(
                    getApplicationContext(), "Transports ordered in price", Toast.LENGTH_SHORT)
                .show();
            if (price_clicked == false) {
              price_clicked = true;
              time_clicked = false;
              cur = dbHelper.getData(myquery + " order by transportation.cost" + " asc");
              adpater1.cursor = cur;
              System.out.println("arrange");
              adpater1.notifyDataSetChanged();
            }
          }
        });

    timeBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            // TODO Auto-generated method stub
            @SuppressWarnings("unused")
            String arrange = selectQuery("cost", true);
            Toast.makeText(
                    getApplicationContext(), "Transports ordered in time", Toast.LENGTH_SHORT)
                .show();
            if (time_clicked == false) {
              price_clicked = false;
              time_clicked = true;
              cur = dbHelper.getData(myquery + " order by transportation.interval" + " asc");
              adpater1.cursor = cur;
              adpater1.notifyDataSetChanged();
            }
          }
        });

    dbHelper = new MySQLiteHelper(getApplicationContext());

    if (shared.vehicle != "all") v_id = dbHelper.getIdForName(dbHelper.TAG_TYPE, shared.vehicle);

    try {
      myquery = selectQuery("cost", true);

    } catch (Exception e) {

    }

    cur = dbHelper.getData(myquery);

    try {
      if (cur.getCount() == 0) {
        // here cur is null so we will have to check if direct path is
        // possible without other search criteria before giving
        // suggestions
        myquery = selectQuery("cost", false);
        Cursor cur1 = dbHelper.getData(myquery);

        if (cur1.getCount() == 0) {

          head = true;
          Intent intentnomatch = new Intent(getApplicationContext(), NoMatchFound.class);

          startActivityForResult(intentnomatch, 2);

        } else {

          // --------------------
          list.setVisibility(View.GONE);
          tvnomatchfound.setVisibility(View.VISIBLE);
        }
      }
    } catch (Exception e) {

    }

    adpater1 = new MyArrayAdapter1(getApplicationContext(), cur);
    setListAdapter(adpater1);

    new HomeFragment().refresh();
  }
 public void open() throws SQLException {
   database = dbHelper.getWritableDatabase();
 }
Exemple #20
0
 public void close() {
   sqlHelper.close();
 }
  public void onClick(View v) {
    cinput1 = (EditText) findViewById(R.id.username_field);
    input1 = cinput1.getText().toString();

    cinput2 = (EditText) findViewById(R.id.password_field);
    input2 = cinput2.getText().toString();

    if (v.getId() == R.id.login_button) {

      if (checkFormat(input1) && checkFormat(input2)) {

        ArrayList<User> users = new ArrayList<User>(db.getAllUsers());

        boolean contains = false;

        for (int i = 0; i < users.size(); i++) {

          if (users.get(i).getUsername().equals(input1)
              && users.get(i).getPassword().equals(input2)) {

            contains = true;
            if (contains) {
              System.out.println("Contains==True");
              loggedUser = new User(users.get(i));
              loggedId = loggedUser.getId();
              loggedUsername = loggedUser.getUsername();

              break;
            }
          }
        }

        if (contains) {
          AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
          dlgAlert.setMessage("Successfully Logged in");
          dlgAlert.setPositiveButton(
              "OK",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  Intent I = new Intent(getApplicationContext(), CancelHold.class);

                  // ***PASS INFO TO RESULTS***
                  Bundle extraInfo = new Bundle();

                  // transactionStuff

                  extraInfo.putString("username", loggedUsername);
                  extraInfo.putInt("id", loggedId);
                  I.putExtras(extraInfo);

                  startActivity(I);
                }
              });
          dlgAlert.setCancelable(true);
          dlgAlert.create().show();
        }
        if (!contains) {
          AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
          dlgAlert.setMessage("Sorry The Account Does Not Exist or Passowrd Is Incorrect.");
          dlgAlert.setPositiveButton(
              "OK",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
              });
          dlgAlert.setCancelable(true);
          dlgAlert.create().show();
        }
      } else {
        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
        dlgAlert.setMessage("Your Username or Password are not correctly formatted! Please Retry!");
        dlgAlert.setPositiveButton(
            "OK",
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {}
            });
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
      }
    }
  }
  private void populateMyMovies(ListView tLV) throws ParseException {
    List<Movie> movies = db.getAllMovies(sortStr, sortDir);

    List<Map<String, String>> list = new ArrayList<Map<String, String>>();

    if (movies.size() < 1) {

      toastMessage(MainActivity.this, getString(R.string.no_movie_notice));

    } else {

      for (Movie i : movies) {
        Map map = new HashMap();
        map.put("id", i.getId());
        map.put("title", i.getTitle());

        String target = i.getDateStr();
        DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
        DateFormat newf = new SimpleDateFormat("EEE, MMM d, yyyy", Locale.ENGLISH);
        Date mDate = df.parse(target);
        String newDate = newf.format(mDate);

        map.put("date", newDate);
        map.put("rating", i.getRating());
        map.put("lat", String.valueOf(i.getVenue().getLat()));
        map.put("lng", String.valueOf(i.getVenue().getLng()));
        map.put("type", i.getVenue().getVenue_type());
        map.put("venue_name", i.getVenue().getVenue_name());
        list.add(map);
      }

      movieAdapter =
          new SimpleAdapter(
              this,
              list,
              R.layout.my_movies_layout,
              new String[] {"title", "date", "rating", "type"},
              new int[] {
                R.id.my_movie_title, R.id.my_movie_date, R.id.my_movie_rating, R.id.my_movie_icon
              });
      movieAdapter.setViewBinder(new MyMovieBinder());
      tLV.setAdapter(movieAdapter);
      tLV.setLongClickable(true);

      tLV.setOnItemClickListener(
          new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              Map item = (Map) parent.getAdapter().getItem(position);
              LatLng latlong =
                  new LatLng(
                      Double.valueOf(item.get("lat").toString()),
                      Double.valueOf(item.get("lng").toString()));

              mMap.clear();
              Marker marker =
                  mMap.addMarker(
                      new MarkerOptions()
                          .position(latlong)
                          .title(item.get("title").toString())
                          .snippet(item.get("venue_name").toString()));

              // Zoom in, animating the camera.
              mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlong, 13), 800, null);
              marker.showInfoWindow();
            }
          });
    }
  }
 public void close() {
   dbHelper.close();
 }
  public String selectQuery(String order, boolean check) {
    String MULTIPLE_VALID_ROUTE = "";
    String single_route = "";
    String ourCase = "";
    String myquery =
        "select "
            + tablehelper.TransportationColumns.CONTACT_PHONE
            + ", "
            + tablehelper.TransportationColumns.DEPART_TIME
            + ", "
            + tablehelper.TransportationColumns.ARRIVAL_TIME
            + ", "
            + tablehelper.TransportationColumns.COST
            + ", "
            + tablehelper.TransportationColumns.REMARKS
            + ", "
            + tablehelper.TransportationColumns.TYPE_ID
            + ", "
            + tablehelper.TransportationColumns.ID
            + ", "
            + tablehelper.TransportationColumns.INTERVAL
            + ", "
            + tablehelper.TransportationColumns.ROUTE_ID
            + ", "
            + tablehelper.CompanyColumns.NAME
            + ", "
            + tablehelper.RouteColumns.FULL_ROUTE
            + " from "
            + tablehelper.TransportationColumns.TABLENAME
            + " JOIN "
            + tablehelper.ScheduleColumns.TABLENAME
            + " ON "
            + tablehelper.ScheduleColumns.TRANSPORTATION_ID
            + " = "
            + tablehelper.TransportationColumns.ID
            + " JOIN "
            + tablehelper.CompanyColumns.TABLENAME
            + " ON "
            + tablehelper.CompanyColumns.ID
            + " = "
            + tablehelper.TransportationColumns.COMPANY_ID
            + " JOIN "
            + tablehelper.RouteColumns.TABLENAME
            + " ON "
            + tablehelper.TransportationColumns.ROUTE_ID
            + " = "
            + tablehelper.RouteColumns.ID
            + " where route.full_route like '%"
            + shared.fromString
            + "%' and route.full_route like '%"
            + shared.toString
            + "%' and ('"
            + shared.fromString
            + "' = (select name from node where name  = '"
            + shared.fromString
            + "')) and ('"
            + shared.toString
            + "' = (select name from node where name = '"
            + shared.toString
            + "'))";
    if (check) myquery = appendParameterToQuery(myquery);
    myquery = myquery + " order by transportation." + order + " asc";

    cur = dbHelper.getData(myquery);
    cur.moveToFirst();
    int row_count = cur.getCount();

    if (cur.getCount() == 0) {
      ourCase = "NO_ROUTE_ATALL_JPT";
    }
    if (row_count == 1) {
      ourCase = "SINGLE_ROUTE";
      int r_id = Integer.parseInt(cur.getString(cur.getColumnIndex("route_id")));
      String quer1 =
          "select route_node.id from route_node where route_id = "
              + r_id
              + " and node_id = (select id from node where name = '"
              + shared.fromString
              + "')";
      String quer2 =
          "select route_node.id from route_node where route_id = "
              + r_id
              + " and node_id = (select id from node where name = '"
              + shared.toString
              + "')";
      Cursor cur1 = dbHelper.getData(quer1);
      Cursor cur2 = dbHelper.getData(quer2);
      cur1.moveToFirst();
      cur2.moveToFirst();
      List<Integer> r_n_id = new ArrayList<Integer>();
      r_n_id.add(Integer.parseInt(cur1.getString(cur1.getColumnIndex("id"))));
      r_n_id.add(Integer.parseInt(cur2.getString(cur2.getColumnIndex("id"))));
      if (r_n_id.get(0) < r_n_id.get(1)) {
        single_route =
            "select "
                + tablehelper.TransportationColumns.CONTACT_PHONE
                + ", "
                + tablehelper.TransportationColumns.DEPART_TIME
                + ", "
                + tablehelper.TransportationColumns.ARRIVAL_TIME
                + ", "
                + tablehelper.TransportationColumns.COST
                + ", "
                + tablehelper.TransportationColumns.REMARKS
                + ", "
                + tablehelper.TransportationColumns.TYPE_ID
                + ", "
                + tablehelper.TransportationColumns.ID
                + ", "
                + tablehelper.TransportationColumns.INTERVAL
                + ", "
                + tablehelper.TransportationColumns.ROUTE_ID
                + ", "
                + tablehelper.CompanyColumns.NAME
                + ", "
                + tablehelper.RouteColumns.FULL_ROUTE
                + " from "
                + tablehelper.TransportationColumns.TABLENAME
                + " JOIN "
                + tablehelper.ScheduleColumns.TABLENAME
                + " ON "
                + tablehelper.ScheduleColumns.TRANSPORTATION_ID
                + " = "
                + tablehelper.TransportationColumns.ID
                + " JOIN "
                + tablehelper.CompanyColumns.TABLENAME
                + " ON "
                + tablehelper.CompanyColumns.ID
                + " = "
                + tablehelper.TransportationColumns.COMPANY_ID
                + " JOIN "
                + tablehelper.RouteColumns.TABLENAME
                + " ON "
                + tablehelper.TransportationColumns.ROUTE_ID
                + " = "
                + tablehelper.RouteColumns.ID
                + " where route.full_route like '%"
                + shared.fromString
                + "%' and route.full_route like '%"
                + shared.toString
                + "%' and route_id = "
                + r_id;

      } else {
        ourCase = "NO_ROUTE_ATALL_JPT";
        // return "select * from route where name = 'aaa'";
      }
    }
    if (row_count > 1) {
      ourCase = "MULTIPLE_ROUTE";
      int correct_count = 0;

      List<Integer> r_id = new ArrayList<Integer>();
      List<Integer> r_id_valid = new ArrayList<Integer>();
      cur.moveToFirst();
      while (!cur.isAfterLast()) {
        r_id.add(Integer.parseInt(cur.getString(cur.getColumnIndex("route_id"))));
        cur.moveToNext();
      }
      int i = 0;
      while (i < r_id.size()) {
        String quer1 =
            "select route_node.id from route_node where route_id = "
                + r_id.get(i)
                + " and node_id = (select id from node where name = '"
                + shared.fromString
                + "')";
        String quer2 =
            "select route_node.id from route_node where route_id = "
                + r_id.get(i)
                + " and node_id = (select id from node where name = '"
                + shared.toString
                + "')";
        Cursor cur1 = dbHelper.getData(quer1);
        Cursor cur2 = dbHelper.getData(quer2);
        List<Integer> r_n_id = new ArrayList<Integer>();
        cur1.moveToFirst();
        cur2.moveToFirst();
        r_n_id.add(Integer.parseInt(cur1.getString(cur1.getColumnIndex("id"))));
        r_n_id.add(Integer.parseInt(cur2.getString(cur2.getColumnIndex("id"))));
        Log.d("crossvoer", "values of r_n_id:" + r_n_id);
        if (r_n_id.get(0) < r_n_id.get(1)) {
          // save r_id in another list
          r_id_valid.add(r_id.get(i));
          correct_count++;
        }
        i++;
      }
      if (correct_count == 0) {
        ourCase = "NO_ROUTE_ATALL_JPT";
      }
      if (correct_count > 0) {
        ourCase = "MULTIPLE_ROUTE";
      }
      StringBuilder MULTIPLE_ROUTE_VALID_ROUTE = new StringBuilder();
      MULTIPLE_ROUTE_VALID_ROUTE.append(
          "select "
              + tablehelper.TransportationColumns.CONTACT_PHONE
              + ", "
              + tablehelper.TransportationColumns.DEPART_TIME
              + ", "
              + tablehelper.TransportationColumns.ARRIVAL_TIME
              + ", "
              + tablehelper.TransportationColumns.COST
              + ", "
              + tablehelper.TransportationColumns.REMARKS
              + ", "
              + tablehelper.TransportationColumns.TYPE_ID
              + ", "
              + tablehelper.TransportationColumns.ID
              + ", "
              + tablehelper.TransportationColumns.INTERVAL
              + ", "
              + tablehelper.TransportationColumns.ROUTE_ID
              + ", "
              + tablehelper.CompanyColumns.NAME
              + ", "
              + tablehelper.RouteColumns.FULL_ROUTE
              + " from "
              + tablehelper.TransportationColumns.TABLENAME
              + " JOIN "
              + tablehelper.ScheduleColumns.TABLENAME
              + " ON "
              + tablehelper.ScheduleColumns.TRANSPORTATION_ID
              + " = "
              + tablehelper.TransportationColumns.ID
              + " JOIN "
              + tablehelper.CompanyColumns.TABLENAME
              + " ON "
              + tablehelper.CompanyColumns.ID
              + " = "
              + tablehelper.TransportationColumns.COMPANY_ID
              + " JOIN "
              + tablehelper.RouteColumns.TABLENAME
              + " ON "
              + tablehelper.TransportationColumns.ROUTE_ID
              + " = "
              + tablehelper.RouteColumns.ID
              + " where route.full_route like '%"
              + shared.fromString
              + "%' and route.full_route like '%"
              + shared.toString
              + "%' and route_id in (");
      Iterator<Integer> it = r_id_valid.iterator();
      while (it.hasNext()) {
        MULTIPLE_ROUTE_VALID_ROUTE.append(it.next());
        MULTIPLE_ROUTE_VALID_ROUTE.append(",");
      }
      MULTIPLE_ROUTE_VALID_ROUTE.append("0)");
      MULTIPLE_VALID_ROUTE = MULTIPLE_ROUTE_VALID_ROUTE.toString();
    } // end of if
    if (ourCase.equals("NO_ROUTE_ATALL_JPT")) {

      return "select full_route from route where name = 'aaa'";
    } else if (ourCase.equals("SINGLE_ROUTE")) {
      return single_route;
    } else if (ourCase.equals("MULTIPLE_ROUTE")) {
      return MULTIPLE_VALID_ROUTE;
    } else return "";
  }