Untitled
unknown
java
a year ago
3.3 kB
5
Indexable
Never
package com.example.weighttracker; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; public class MainActivity extends AppCompatActivity { private EditText weightEditText; private Button addButton; private ListView weightListView; private SQLiteDatabase database; private SimpleCursorAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); weightEditText = findViewById(R.id.weightEditText); addButton = findViewById(R.id.addButton); weightListView = findViewById(R.id.weightListView); // Veritabanı oluşturma ve açma database = openOrCreateDatabase("WeightDB", MODE_PRIVATE, null); database.execSQL("CREATE TABLE IF NOT EXISTS weights (_id INTEGER PRIMARY KEY AUTOINCREMENT, weight REAL NOT NULL, date TEXT NOT NULL)"); // Kaydedilen ağırlıkları tarih sırasına göre listeleme Cursor cursor = database.rawQuery("SELECT * FROM weights WHERE active = 1 ORDER BY date DESC", null); String[] columns = {"weight", "date"}; int[] views = {R.id.weightTextView, R.id.dateTextView}; adapter = new SimpleCursorAdapter(this, R.layout.weight_item, cursor, columns, views, 0); weightListView.setAdapter(adapter); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Kilo verisini al String weightString = weightEditText.getText().toString().trim(); if (weightString.isEmpty()) { Toast.makeText(MainActivity.this, "Lütfen bir ağırlık girin", Toast.LENGTH_SHORT).show(); return; } double weight = Double.parseDouble(weightString); // Tarih bilgisini oluştur DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()); String date = dateFormat.format(Calendar.getInstance().getTime()); // Veritabanına kaydet database.execSQL("INSERT INTO weights (weight, date, active) VALUES (?, ?, 1)", new Object[] {weight, date}); // ListView'i güncelle Cursor cursor = database.rawQuery("SELECT * FROM weights WHERE active = 1 ORDER BY date DESC", null); adapter.changeCursor(cursor); adapter.notifyDataSetChanged(); // Giriş alanını temizle weightEditText.setText(""); } }); } @Override protected void onDestroy() { super.onDestroy(); // Veritabanı bağlantısını kapat database.close(); } }