Android создание ListView

Столкнулся с проблемой, получаю с сайта id, автора, название и ссылку на музыку, записываю в локальную базу данных на самом устройстве, потом их вывожу в ListView. Но мне надо по получить id выбранной аудиозаписи из списка ListView.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    String server_name = "http://youtdomain.ru";

    ListView list_music;

    SQLiteDatabase musicDBlocal;
    HttpURLConnection conn;
    Cursor cursor;
    Thread thr;
    ContentValues new_mus;
    Long last_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicDBlocal = openOrCreateDatabase("musicDBlocal.db",
                Context.MODE_PRIVATE, null);
        musicDBlocal
                .execSQL("CREATE TABLE IF NOT EXISTS music (_id integer primary key autoincrement, id integer, author, name, url)");

        startLoop();

        list_music = (ListView)findViewById(R.id.list_music);
        create_lv();

        list_music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    @SuppressLint("SimpleDateFormat")
    public void create_lv() {

        Cursor cursor = musicDBlocal.rawQuery(
                "SELECT * FROM music", null);
        if (cursor.moveToFirst()) {
            // если в базе есть элементы соответствующие
            // нашим критериям отбора

            // создадим массив, создадим hashmap и заполним его результатом
            // cursor
            ArrayList<HashMap<String, Object>> mList = new ArrayList<HashMap<String, Object>>();
            HashMap<String, Object> hm;

           do{
               hm = new HashMap<>();
               hm.put("author", cursor.getString(cursor.getColumnIndex("author")));
               hm.put("name", cursor.getString(cursor.getColumnIndex("name")));
               mList.add(hm);
           } while (cursor.moveToNext());


            // покажем lv
            SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
                    mList, R.layout.audio_list, new String[] { "author",
                    "name" },
                    new int[] { R.id.autor, R.id.name });

            list_music.setAdapter(adapter);
            cursor.close();

        }

        Log.i("chat",
                "+ ChatActivity ======================== обновили поле чата");

    }

    private void startLoop() {

        thr = new Thread(new Runnable() {

            // ansver = ответ на запрос
            // lnk = линк с параметрами
            String ansver, lnk;

            public void run() {

                while (true) { // стартуем бесконечный цикл

                    // глянем локальную БД на наличие сообщщений чата
                    cursor = chatDBlocal.rawQuery(
                            "SELECT * FROM music ORDER BY id", null);

                    // если какие-либо сообщения есть - формируем запрос
                    // по которому получим только новые сообщения
                    if (cursor.moveToLast()) {
                        last_id = cursor.getLong(cursor
                                .getColumnIndex("id"));
                        lnk = server_name + "/music.php?id="
                                + last_id.toString();

                        // если сообщений в БД нет - формируем запрос
                        // по которому получим всё
                    } else {
                        lnk = server_name + "/music.php?id=0";
                    }

                    cursor.close();

                    // создаем соединение ---------------------------------->
                    try {
                        Log.i("chat",
                                "+ FoneService --- ОТКРОЕМ СОЕДИНЕНИЕ   " + lnk);

                        conn = (HttpURLConnection) new URL(lnk)
                                .openConnection();
                        conn.setReadTimeout(10000);
                        conn.setConnectTimeout(15000);
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
                        conn.setDoInput(true);
                        conn.connect();

                    } catch (Exception e) {
                        Log.i("chat", "+ FoneService ошибка: " + e.getMessage());
                    }
                    // получаем ответ ---------------------------------->
                    try {
                        InputStream is = conn.getInputStream();
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(is, "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        String bfr_st = null;
                        while ((bfr_st = br.readLine()) != null) {
                            sb.append(bfr_st);
                        }

                        Log.i("chat", "+ FoneService - полный ответ сервера:\n"
                                + sb.toString());
                        // сформируем ответ сервера в string
                        // обрежем в полученном ответе все, что находится за "]"
                        // это необходимо, т.к. json ответ приходит с мусором
                        // и если этот мусор не убрать - будет невалидным
                        ansver = sb.toString();
                        ansver = ansver.substring(0, ansver.indexOf("]") + 1);

                        is.close(); // закроем поток
                        br.close(); // закроем буфер

                    } catch (Exception e) {
                        Log.i("chat", "+ FoneService ошибка: " + e.getMessage());
                    } finally {
                        conn.disconnect();
                        Log.i("chat",
                                "+ FoneService --------------- ЗАКРОЕМ СОЕДИНЕНИЕ");
                    }

                    // запишем ответ в БД ---------------------------------->
                    if (ansver != null && !ansver.trim().equals("")) {

                        Log.i("chat",
                                "+ FoneService ---------- ответ содержит JSON:");

                        try {
                            // ответ превратим в JSON массив
                            JSONArray ja = new JSONArray(ansver);
                            JSONObject jo;

                            Integer i = 0;

                            while (i < ja.length()) {

                                // разберем JSON массив построчно
                                jo = ja.getJSONObject(i);

                                Log.i("chat",
                                        "=================>>> "
                                                + jo.getLong("id")
                                                + " | "
                                                + jo.getString("author")
                                                + " | " + jo.getString("name")
                                                + " | " + jo.getString("url"));

                                // создадим новое сообщение
                                new_mus = new ContentValues();
                                new_mus.put("id", jo.getInt("id"));
                                new_mus.put("author", jo.getString("author"));
                                new_mus.put("name", jo.getString("name"));
                                new_mus.put("url", jo.getString("url"));
                                // запишем новое сообщение в БД
                                musicDBlocal.insert("music", null, new_mus);
                                new_mess.clear();

                                i++;

                            }
                        } catch (Exception e) {
                            // если ответ сервера не содержит валидный JSON
                            Log.i("ee",
                                    "+ FoneService ---------- ошибка ответа сервера:\n"
                                            + e.getMessage());
                        }
                    } else {
                        // если ответ сервера пустой
                        Log.i("ee",
                                "+ FoneService ---------- ответ не содержит JSON!");
                    }

                    try {
                        Thread.sleep(15000);
                    } catch (Exception e) {
                        Log.i("ee",
                                "+ FoneService - ошибка процесса: "
                                        + e.getMessage());
                    }
                }
            }
        });

        thr.setDaemon(true);
        thr.start();

    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:background="@color/colorBackground">

    <ListView
        android:id="@+id/list_music"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

audio_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="59dp"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <ImageView
            android:id="@+id/music_img"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            tools:srcCompat="@mipmap/ic_music_120" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="51dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="$track_name"
                android:textColor="@color/colorWhite" />

            <TextView
                android:id="@+id/autor"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="$track_autor"
                android:textColor="@color/colorWhite" />
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Пожалуйста, пример кода. Спасибо.


Ответы (0 шт):