Skip to content

Instantly share code, notes, and snippets.

@anta40
Created September 21, 2022 13:44
Show Gist options
  • Save anta40/dda0fc9ecb1c77ec4238ab2ba5ad43aa to your computer and use it in GitHub Desktop.
Save anta40/dda0fc9ecb1c77ec4238ab2ba5ad43aa to your computer and use it in GitHub Desktop.
Country demo
package com.anta40.app.countrycruddemo;
import androidx.annotation.MainThread;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnAddCountry;
Button btnSave;
EditText edtName, edtPopulation;
RecyclerView rvCountry;
CountryAdapter countryAdapter;
SQLiteDBHandler dbHandler;
List<Country> countries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new SQLiteDBHandler(getApplicationContext());
countries = dbHandler.getAllCountries();
rvCountry = (RecyclerView) findViewById(R.id.rvCountry);
rvCountry.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
countryAdapter = new CountryAdapter(countries);
rvCountry.setAdapter(countryAdapter);
btnAddCountry = (Button) findViewById(R.id.btnAddCountry);
btnAddCountry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.dialog_input_country, null);
AlertDialog.Builder adBuilder = new AlertDialog.Builder(MainActivity.this);
adBuilder.setView(popupView);
btnSave = (Button) popupView.findViewById(R.id.btnSave);
edtName = (EditText) popupView.findViewById(R.id.edtName);
edtPopulation = (EditText) popupView.findViewById(R.id.edtPopulation);
AlertDialog dialog = adBuilder.create();
dialog.setCancelable(true);
dialog.show();
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
Country newCountry = new Country(0, edtName.getText().toString(),
Integer.parseInt(edtPopulation.getText().toString()));
dbHandler.addCountry(newCountry);
dialog.dismiss();
countries = dbHandler.getAllCountries();
countryAdapter.updateAndRefreshData(countries);
}
});
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment