Problem showing id on home screen when using sqlite in android studio

Asked

Viewed 36 times

0

i am developing an app in android studio where it shows the id and name of an anime q comes from the database when making the anime registration on the anime registration screen, however when deleting an anime table in the anime edit screen, when it returns the home screen that shows the id and name of the anime, it shows for example, if I have 3 anime registered and I delete the 2, the third it n gets the id 2, i’m using an auto increment when creating the id in the database table and if I delete everything and start creating the anime list, when finishing the registration it starts with the id with 1 more than the last q was and n of the 0, type with everything erased was for when I add a new id is 1 and not for example 7 or 8, assuming that when deleting the list had registered 6 or 7 anime. what I want to do is the following how to add and show the anime and the id is right if register 1 anime, it shows 1 and the name of the anime, register 2 and show 2 and the name and so it goes, however when deleting an anime, i want all ids to be right tbm and n type as if I had jumped for example I did 7 animes and deleted 2, 4 and 6 and when coming back on the home screen keep showing ids 1,3,5,7, I want after deleting an anime the list stay straight in case I delete the anime msm that I said up there, stay 1,2,3,4. This is possible to do if yes please someone can help me, I will be posting the code of the classes and layout here below in the answers.

  • This is the default behavior of auto_increment , I think you can’t change, besides causing errors if you change because, delete and Edit, makes the operations most of the time based on id. You can however create an attribute and place the value according to its position in your Arraylist and display it instead of id.

  • and how can I do it man, you can send me the code and where I need to put this code through the codes I sent there, only new in programming and n know mts things, I did it there through a course

  • but n to do the way q ta ai, because my I am using the data that go to the database and already there it uses only the values q are in the text field, maybe if I did as you say, type I created a code field for the user to type and then it showed on the main screen this code and the name of the anime, however when I will put the id of the error code field says q n there is the column in the database msm if I have already created the column and only accept if it is this id

2 answers

0

mainActivity code

public class Mainactivity extends Appcompatactivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BancoDeDados bancoDeDados = new BancoDeDados(getBaseContext());

    final Cursor cursor = bancoDeDados.obterAnimes();

    String[] nomeCampos = new String[] {"_id", "nome"};

    int[] idViews = new int[] {R.id.labelId, R.id.labelTitulo};

    SimpleCursorAdapter adaptador = new SimpleCursorAdapter(getBaseContext(), R.layout.modelo_lista,cursor,nomeCampos,idViews,0);

    ListView lista = (ListView)findViewById(R.id.listaDeAnimes);
    lista.setAdapter(adaptador);

    lista.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            cursor.moveToPosition(position);
            Intent intent = new Intent(MainActivity.this, EditarAnime.class);
            intent.putExtra("id", cursor.getInt(cursor.getColumnIndexOrThrow("_id")));
            startActivity(intent);
            finish();
        }
    });
}

public void abrirTelaCriarNovoAnime(View v){
    Intent startNewActivity = new Intent(this, CriarAnime.class);
    startActivity(startNewActivity);
}

}

screen code create anime

public class Criaanime extends Appcompatactivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_criar_anime);
}

public void voltar (View v){
    Intent startNewActivity = new Intent(this, MainActivity.class);
    startActivity(startNewActivity);
}

public void criarAnime (View v){

    BancoDeDados bancoDeDados = new BancoDeDados(getBaseContext());
    EditText nome = (EditText) findViewById(R.id.campoNome);
    EditText numeroEpisodios = (EditText) findViewById(R.id.campoNumeroEpisodios);
    EditText temporadas = (EditText) findViewById(R.id.campoTemporadas);

    if( TextUtils.isEmpty(nome.getText())){

        nome.setError( "Informe o nome do anime" );

    }if (TextUtils.isEmpty(numeroEpisodios.getText())){
        numeroEpisodios.setError("Informe o número de episódios");
    }
    if (TextUtils.isEmpty(temporadas.getText())){
        temporadas.setError("Informe o a quantidade de temporadas");
    }
    else{
        boolean resultado = bancoDeDados.criarAnime(nome.getText().toString(), numeroEpisodios.getText().toString(), temporadas.getText().toString());

        if (resultado) {
            Toast.makeText(this, "Anime criado com sucesso!", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Infelizmente ocorreu um erro, tente novamente.", Toast.LENGTH_SHORT).show();
        }

        voltar(v);
    }
}

}

screen code edits anime

public class Editaranime extends Appcompatactivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edita_anime);

    BancoDeDados bancoDeDados = new BancoDeDados(getBaseContext());
    final Cursor cursor = bancoDeDados.consultarAnimePeloId(this.getIntent().getIntExtra("id",0));

    EditText nome = (EditText) findViewById(R.id.campoNome);
    EditText numeroEpisodios = (EditText) findViewById(R.id.campoNumeroEpisodios);
    EditText tempordas = (EditText) findViewById(R.id.campoTemporadas);

    nome.setText(cursor.getString(cursor.getColumnIndexOrThrow("nome")));
    numeroEpisodios.setText(cursor.getString(cursor.getColumnIndexOrThrow("numeroEpisodios")));
    tempordas.setText(cursor.getString(cursor.getColumnIndexOrThrow("temporadas")));
    
}

public void voltar(View v){
    Intent startNewActivity = new Intent(this, MainActivity.class);
    startActivity(startNewActivity);
}


public void atualizarAnime(View v){

    BancoDeDados bancoDeDados = new BancoDeDados(getBaseContext());

    EditText nome = (EditText) findViewById(R.id.campoNome);
    EditText numeroEpisodios = (EditText) findViewById(R.id.campoNumeroEpisodios);
    EditText tempordas = (EditText) findViewById(R.id.campoTemporadas);


    try {
        bancoDeDados.atualizaAnime(this.getIntent().getIntExtra("id",0),nome.getText().toString(), numeroEpisodios.getText().toString(), tempordas.getText().toString());
        Toast.makeText(this, "Anime atualizada com sucesso!", Toast.LENGTH_SHORT).show();
    }catch (Exception ex) {
        Toast.makeText(this, "Não foi possível atualizar o anime, tente novamente!", Toast.LENGTH_SHORT).show();
    }
    voltar(v);
}

public void excluiAnime(View v, SQLiteDatabase db){
    BancoDeDados bancoDeDados = new BancoDeDados(getBaseContext());

    EditText nome = (EditText) findViewById(R.id.campoNome);
    EditText numeroEpisodios = (EditText) findViewById(R.id.campoNumeroEpisodios);
    EditText tempordas = (EditText) findViewById(R.id.campoTemporadas);

    try {

        bancoDeDados.excluiAnime(this.getIntent().getIntExtra("id",0));
        

        Toast.makeText(this, "Anime excluído com sucesso!", Toast.LENGTH_SHORT).show();


    }catch (Exception ex){
        Toast.makeText(this, "Não foi possível excluir o anime, tente novamente!", Toast.LENGTH_SHORT).show();
    }
    voltar(v);
}

}

code of the class manage bank

public class Gerenciarbanco extends Sqliteopenhelper {

public static final String NOME_BANCO = "bancoDeDados.db";
public static final int VERSAO = 1;

public GerenciarBanco(Context context){
    super(context,NOME_BANCO,null,VERSAO);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String sql="CREATE TABLE animes (_id integer primary key autoincrement, nome text, numeroEpisodios text, temporadas text)";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS animes");
    onCreate(db);
}

}

database class code

public class Bancodedados {

public SQLiteDatabase banco;
public GerenciarBanco gerenciarBanco;

public BancoDeDados(Context context){
    gerenciarBanco = new GerenciarBanco(context);
}

public boolean criarAnime(String nome, String numeroEpisodios, String temporadas){

    banco = gerenciarBanco.getWritableDatabase();

    ContentValues valores = new ContentValues();
    valores.put("nome", nome);
    valores.put("numeroEpisodios", numeroEpisodios);
    valores.put("temporadas", temporadas);

    long resultado = banco.insert("animes", null, valores);
    banco.close();

    return resultado > 0;
}

public Cursor obterAnimes(){

    String[] campos = {"_id", "nome"};
    SQLiteDatabase db = gerenciarBanco.getReadableDatabase();
    Cursor cursor = db.query("animes", campos, null,null,null,null, "_id ASC");

    if (cursor != null){
        cursor.moveToFirst();
    }

    db.close();
    return cursor;
}

public void atualizaAnime(int id, String nome, String numeroEpisodios, String temporadas){
    SQLiteDatabase db = gerenciarBanco.getReadableDatabase();
    String where = "_id = " + id;

    ContentValues valores = new ContentValues();
    valores.put("nome", nome);
    valores.put("numeroEpisodios", numeroEpisodios);
    valores.put("temporadas", temporadas);

    db.update("animes", valores, where, null);
    db.close();
}

public void excluiAnime(int id){
    SQLiteDatabase db = gerenciarBanco.getReadableDatabase();
    String where = "_id = " + id;
    db.delete("animes", where, null);
    db.close();
}

public Cursor consultarAnimePeloId(int notaId){
    Cursor cursor;
    String[] campos = {"_id", "nome", "numeroEpisodios", "temporadas"};
    String where = "_id = " + notaId;
    SQLiteDatabase db = gerenciarBanco.getReadableDatabase();
    cursor = db.query("animes", campos, where, null,null,null,null,null);

    if (cursor !=null){
        cursor.moveToFirst();
    }
    db.close();
    return cursor;
}

}

I will send the xml codes of the layout.

0

xml from mainActivity screen

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/nome"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="ANIMES"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:textSize="24sp"
    android:textAlignment="center"
    android:textColor="@color/yellow"
    android:fontFamily="sans-serif-black"></TextView>

<ListView
    android:id="@+id/listaDeAnimes"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.92"
    android:paddingTop="40dp"></ListView>

<Button
    android:id="@+id/botaoCriarAnime"
    android:text="Adicionar Anime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    android:layout_margin="16dp"
    android:onClick="abrirTelaCriarNovoAnime"
    android:focusable="true"/>

xml screen create anime

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    android:weightSum="1"
    tools:context=".ui.activity.CriarAnime">

    <TextView
        android:id="@+id/nome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Criar Novo Anime"
        android:textColor="@color/black"
        android:fontFamily="sans-serif-black"
        android:textAlignment="center"
        android:textSize="24sp"/>

    <EditText
        android:id="@+id/campoNome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Nome do Anime:"
        android:inputType="textCapWords"/>

    <EditText
        android:id="@+id/campoNumeroEpisodios"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Número de Episódios:"
        android:inputType="text"/>

    <EditText
        android:id="@+id/campoTemporadas"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Quantidade de Temporadas:"
        android:inputType="text"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/botaoCriar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:text="Criar"
            android:textAlignment="center"
            android:onClick="criarAnime"/>

        <Button
            android:id="@+id/botaoCancelar"
            android:text="Cancelar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="voltar"/>
    </LinearLayout>
</LinearLayout>

xml screen edits anime

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="64dp"
    android:paddingTop="16dp"
    android:paddingRight="64dp"
    android:paddingBottom="16dp"
    android:weightSum="1"
    tools:context=".ui.activity.EditarAnime">

    <TextView
        android:id="@+id/nome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Atualizar Anime"
        android:textColor="@color/black"
        android:fontFamily="sans-serif-black"
        android:textAlignment="center"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/campoNome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Nome do Anime:"
        android:inputType="textCapWords"/>

    <EditText
        android:id="@+id/campoNumeroEpisodios"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Número de Episódios:"
        android:inputType="text"/>

    <EditText
        android:id="@+id/campoTemporadas"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:hint="Quantidade de Temporadas:"
        android:inputType="text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/botaoGravar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="atualizarAnime"
            android:layout_marginRight="8dp"
            android:text="Gravar"
            android:textAlignment="center" />

        <Button
            android:id="@+id/botaoExcluir"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="excluiAnime"
            android:text="Excluir"/>
    </LinearLayout>
</LinearLayout>

xml of the list template

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/labelId"
    android:text="ID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingRight="10dp"/>

<TextView
    android:id="@+id/labelTitulo"
    android:text="TITULO"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

If anyone can help me solve this issue of ids I appreciate dmssss

Browser other questions tagged

You are not signed in. Login or sign up in order to post.