0

Вобщем задумка такая, что цвет записывается в базу SQL в виде текста в Activity2 а в Activity1 при чтении записей из БД устанавливается заливка ячейки ListViev согласно полученным данным из БД. Я создал адаптер для проверки цвета, но почему то не заполняет ячейки нужными цветами. Так же данные из столбца SQL почему имеют на выходе имя столбца а не данные из ячейки. Подскажите пожалуйста где я ошибся? Я еще только учусь так что не судите строго)

Вот мой код

activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="onClickAdd"/>

    <ListView
        android:id="@+id/list_viev"
        android:layout_width="395dp"
        android:layout_height="715dp"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        >

    </ListView>


</android.support.constraint.ConstraintLayout>

MainActivity

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends AppCompatActivity {
final String LOG_TAG = "myLog";

private ListView lv;
Button addBtn;

DBHelper dbHelper;
SQLiteDatabase db;
long userID = 0;
Cursor cursor;
SimpleCursorAdapter simpleCursorAdapter;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );
    addBtn = findViewById( R.id.button2 );
    lv = findViewById( R.id.list_viev );

    dbHelper = new DBHelper( this );
    Log.d( LOG_TAG, "--------Main2Activity---------инициализация БД и переменных" );
    db = dbHelper.getWritableDatabase();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        userID = extras.getLong( "id" );
    }// если ноль то добавляем
    if (userID > 0) {
        //получаем элемент из БД
        cursor = db.rawQuery( "select * from " + DBHelper.DATABASE_TABLE_NAME + " where " + DBHelper.KEY_ID + "=?", new String[]{String.valueOf( userID )} );
        cursor.moveToFirst();
        cursor.close();
    }

}

public void onClickAdd(View view) {
    Intent intent = new Intent( this, Main2Activity.class );
    startActivity( intent );
    Log.d( LOG_TAG, "--------MainActivity---------Старт активити2 для добавления новой записи нажатие на кнопку +" );
}

@Override
protected void onResume() {
    super.onResume();

    //открываем подключение к БД
    db = dbHelper.getReadableDatabase();

    //получаем данные из бд в виде курсора
    cursor = db.rawQuery( "select * from " + DBHelper.DATABASE_TABLE_NAME, null );
    // определяем, какие столбцы из курсора будут выводиться в ListView
    Log.d( LOG_TAG, "--------MainActivity---------определяем, какие столбцы из курсора будут выводиться в ListView" );
    String[] headers = new String[]{DBHelper.KEY_BACKGROUND};

    // создаем адаптер, передаем в него курсор
    Log.d( LOG_TAG, "--------MainActivity---------создаем адаптер, передаем в него курсор" );

    String nameColor;
    nameColor = DBHelper.KEY_BACKGROUND;
    String[] colrsArray = new String[]{nameColor};

    Log.d( LOG_TAG, nameColor + " text colors" );
    CustomArrayAdapter adapter = new CustomArrayAdapter( this, colrsArray );
    lv.setAdapter( adapter );

    simpleCursorAdapter = new SimpleCursorAdapter( this, R.layout.list_item,
            cursor, headers, new int[]{R.id.colors}, 0 );

    lv.setAdapter( simpleCursorAdapter );
    Log.d( LOG_TAG, "--------MainActivity---------Подключение к БД и получаем список записей" );
}

}

CustomArrayAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomArrayAdapter extends ArrayAdapter<String> {
private Context context;
private String[] stringValues;

public CustomArrayAdapter (Context context, String[] stringValues)
{
    super(context, R.layout.list_item, stringValues);
    this.context = context;
    this.stringValues = stringValues;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.list_item, parent, false);
    TextView textView = (TextView) view.findViewById(R.id.colors);
    LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.llColors);
    textView.setText(stringValues[position]);
    String s = stringValues[position];

    if (s.equals("red"))
    {linearLayout.setBackgroundResource(R.color.red);
    }
    else if (s.equals("orange"))
    {linearLayout.setBackgroundResource(R.color.orange);
    }
    else if (s.equals("yellow"))
    {linearLayout.setBackgroundResource(R.color.yellow);
    }
    else if (s.equals("green"))
    {linearLayout.setBackgroundResource(R.color.green);
    }
    else if (s.equals("vblue"))
    {linearLayout.setBackgroundResource(R.color.light_blue);
    }
    else if (s.equals("blue"))
    {linearLayout.setBackgroundResource(R.color.blue);
    }
    else if (s.equals("violet"))
    {linearLayout.setBackgroundResource(R.color.purple);
    }
    else  linearLayout.setBackgroundResource(R.color.white);
    return view;
}

}

Colors.xml

<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>


<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
<color name="red">#ff0000</color>
<color name="orange">#d24c09</color>
<color name="yellow">#d2c509</color>
<color name="green">#42d209</color>
<color name="light_blue">#01c1f5</color>
<color name="blue">#011df5</color>
<color name="purple">#b001f5</color>
</resources>

DBHelper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

final String LOG_TAG = "myLog";

public static final int DATABASE_VERSION = 5; //версия БД
public static final String DATABASE_NAME = "mydatabase"; // Имя БД
public static final String DATABASE_TABLE_NAME = "todo"; // Имя таблицы

// имена столбцов таблицы
public static final String KEY_ID = "_id";
public static final String KEY_BACKGROUND = "background";


public DBHelper(Context context) {

    super( context, DATABASE_NAME, null, DATABASE_VERSION );

}


@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + DATABASE_TABLE_NAME + " (" + KEY_ID
            + " integer primary key autoincrement,"
            + KEY_BACKGROUND + " TEXT);";

    db.execSQL( query );

    Log.d( LOG_TAG, "--------DBHelper---------создание таблицы" );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL( "drop table if exists " + DATABASE_TABLE_NAME );
    onCreate( db );
    Log.d( LOG_TAG, "--------DBHelper---------обновление таблицы" );
}

}

activity_main2

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">

<EditText
    android:id="@+id/editTextColor"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:text="TextView"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    android:layout_marginEnd="139dp"
    android:text="add"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:onClick="onClick"/>

</android.support.constraint.ConstraintLayout>

Main2Activity

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;


public class Main2Activity extends AppCompatActivity {
final String LOG_TAG = "myLog";

EditText editTextColor;
long userID = 0;
SQLiteDatabase db;
DBHelper dbHelper;
Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main2 );
    editTextColor = findViewById( R.id.editTextColor );

    dbHelper = new DBHelper( this );
    Log.d( LOG_TAG, "--------Main2Activity---------инициализация БД и переменных" );
    db = dbHelper.getWritableDatabase();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        userID = extras.getLong( "id" );
    }// если ноль то добавляем
    if (userID > 0) {
        //получаем элемент из БД
        cursor = db.rawQuery( "select * from " + DBHelper.DATABASE_TABLE_NAME + " where " + DBHelper.KEY_ID + "=?", new String[]{String.valueOf( userID )} );
        cursor.moveToFirst();
        editTextColor.setText( cursor.getString( 1 ) );

        cursor.close();
    }
}

public void onClick(View view) {
    ContentValues contentValues = new ContentValues();
    contentValues.put( DBHelper.KEY_BACKGROUND, editTextColor.getText().toString() );


    if (userID > 0) {
        db.update( DBHelper.DATABASE_TABLE_NAME, contentValues, DBHelper.KEY_ID + "=" + String.valueOf( userID ), null );
    } else {
        db.insert( DBHelper.DATABASE_TABLE_NAME, null, contentValues );
    }
    goHome();
    Log.d( LOG_TAG, "--------Main2Activity---------Сохранение записи в таблицу" );
}

public void goHome() {
    //закрываем БД и возвращаемся в активити
    db.close();
    Intent intent = new Intent( this, MainActivity.class );
    intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP );
    startActivity( intent );
    Log.d( LOG_TAG, "--------Main2Activity---------Возврат в Майн активити" );
}

}

item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llColors"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
    android:id="@+id/colors"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16dp"
    android:textStyle="bold"/>
</LinearLayout>

1 ответ 1

1

После долгих проб и ошибок, и поисков на форумах. Я понял что для того чтобы получить конкретное значение из курсора нужно переопределить SimpleCursorAdapter и метод bindView а не getView

Ниже я оставлю код переопределенного SimpleCursorAdapter для тех кто столкнется с такой же проблемой как и я.

private class MyCursorAdapter extends SimpleCursorAdapter {

    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super( context, layout, c, from, to, flags );
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView( view, context, cursor );

        LinearLayout linearLayout = view.findViewById( R.id.llColors );
        String color = cursor.getString( cursor.getColumnIndex( DBHelper.KEY_BACKGROUND ) );


        if (color.equals( "red" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.red ) );
        } else if (color.equals( "orange" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.orange ) );
        } else if (color.equals( "yellow" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.yellow ) );
        } else if (color.equals( "green" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.green ) );
        } else if (color.equals( "light_blue" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.light_blue ) );
        } else if (color.equals( "blue" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.blue ) );
        } else if (color.equals( "purple" )) {
            linearLayout.setBackgroundColor( getResources().getColor( R.color.purple ) );
        }

    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.