how can i add elements from a DB to a linear layout - android-studio

First of all, sorry if my English is bad cause I'm from Spain.
I create a DB of football players (don't judge, is for school) and I want to show in the linear layout every player I add in the DB.
Here is my main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = findViewById(R.id.insertar);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
if (db != null) {
Toast.makeText(MainActivity.this, "Insertado con éxito.", Toast.LENGTH_LONG).show();
db.close();
}
}
});
}
public void add(View view) {
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
TextView nombreJugador = findViewById(R.id.nombre);
TextView posicionJugador = findViewById(R.id.posicion);
TextView dorsalJugador = findViewById(R.id.dorsal);
if (db != null) {
ContentValues values = new ContentValues();
values.put("nombre", nombreJugador.getText().toString());
values.put("posicion", posicionJugador.getText().toString());
values.put("dorsal", dorsalJugador.getText().toString());
db.close();
}
}
public void changeToShowDB(View v) {
Intent actividad = new Intent(MainActivity.this, MainActivity2.class);
startActivity(actividad);
}
}
And here my other activity in which I have the linear layout and where I want to show the players of the DB.
public class MainActivity2 extends AppCompatActivity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ll = (LinearLayout) findViewById(R.id.linearlayout);
}
public void changeToMain(View v) {
Intent actividad = new Intent(MainActivity2.this, MainActivity.class);
startActivity(actividad);
}
public void submitChoice(View view) {
TextView nombreJugador = findViewById(R.id.nombre);
TextView posicionJugador = findViewById(R.id.posicion);
TextView dorsalJugador = findViewById(R.id.dorsal);
TextView textView = new TextView(this);
textView.setText("text");
ll.addView(textView);
ll.invalidate();
}
}
How could I add the players I just collect from the DB to the linear layout?
First of all, sorry if my English is bad cause I'm from Spain.
I create a DB of football players (don't judge, is for school) and I want to show in the linear layout every player I add in the DB.
Here is my main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = findViewById(R.id.insertar);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
if (db != null) {
Toast.makeText(MainActivity.this, "Insertado con éxito.", Toast.LENGTH_LONG).show();
db.close();
}
}
});
}
public void add(View view) {
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
TextView nombreJugador = findViewById(R.id.nombre);
TextView posicionJugador = findViewById(R.id.posicion);
TextView dorsalJugador = findViewById(R.id.dorsal);
if (db != null) {
ContentValues values = new ContentValues();
values.put("nombre", nombreJugador.getText().toString());
values.put("posicion", posicionJugador.getText().toString());
values.put("dorsal", dorsalJugador.getText().toString());
db.close();
}
}
public void changeToShowDB(View v) {
Intent actividad = new Intent(MainActivity.this, MainActivity2.class);
startActivity(actividad);
}
}
And here my other activity in which I have the linear layout and where I want to show the players of the DB.
public class MainActivity2 extends AppCompatActivity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ll = (LinearLayout) findViewById(R.id.linearlayout);
}
public void changeToMain(View v) {
Intent actividad = new Intent(MainActivity2.this, MainActivity.class);
startActivity(actividad);
}
public void submitChoice(View view) {
TextView nombreJugador = findViewById(R.id.nombre);
TextView posicionJugador = findViewById(R.id.posicion);
TextView dorsalJugador = findViewById(R.id.dorsal);
TextView textView = new TextView(this);
textView.setText("text");
ll.addView(textView);
ll.invalidate();
}
}
How could I add the players I just collect from the DB to the linear layout?

Related

how to send data from popup window to a tabbed activity having fragments?

mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity(having popup window on clicking button)
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}
Get the "igname" String value in onClickListner & also dismiss the dialog before finishing the activity.
entry.setOnClickListener(v -> {
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});

Hide Button if not data in recyclerview

I had created a app in which i have multiple edittext and one buttonwith recyclerviuew and one button which are setvisibilty as Gone.On Button click it add all my data in my recyclerview list with by chnaging visibality of my recycelr view and my button.In my Custom Adapter i am using a image view to delete the item from postion now i want that if it delete all data from list then it should automatically hide my Button and recyclerview.
//Recycler_view Adapter
public class Myviewholder extends RecyclerView.ViewHolder {
public TextView land_Detail, area_detail, s_no1;
public Button delete;
public Myviewholder(View view) {
super(view);
land_Detail = view.findViewById(R.id.hint31);
area_detail = view.findViewById(R.id.hint21);
s_no1 = view.findViewById(R.id.hint11);
delete = view.findViewById(R.id.hint41);
}
}
public Land_adapters(List<Land_list> land_list, Context context) {
this.laand_list = land_list;
this.context = context;
}
#NonNull
#Override
public Land_adapters.Myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.land_list, parent, false);
return new Myviewholder(itemView);
}
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, final int position) {
final Land_list current_year = laand_list.get(position);
holder.area_detail.setText("District :" + current_year.getDistrict_name() + "\n" + "Village :" + current_year.getVillage_name());
holder.s_no1.setText(String.valueOf(position + 1));
holder.land_Detail.setText("Acre :" + current_year.getAcre() + "\n" + "Kanal :" + current_year.getKanal() + "\n" + "Marla :" + current_year.getMarla());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
Land_list theRemovedItem = laand_list.get(position);
// remove your item from data base
laand_list.remove(position); // remove the item from list
notifyItemRemoved(position); // notify the adapter about the removed item
}
});
}
#Override
public int getItemCount() {
return laand_list.size();
}
//how i am using my recycler in mainactivity class
public void final_step() {
// marla_edit.setError(null);
recyclerView = findViewById(R.id.recycler_view_last1);
mAdapter1 = new Land_Adapter(last_Year1);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter1);
Land_list last_year1 = new Land_list(land_acre, land_kanal, village_selected1, land_marla, district_selected1, teshil_selected1, block_selected1, block_code, teshil_code1, village_code1, district_code);
last_Year1.add(last_year1);
mAdapter1.notifyDataSetChanged();
if (!(last_Year1.size() == 0)) {
RelativeLayout linearLayout = findViewById(R.id.linear123);
recyclerView.setVisibility(View.VISIBLE);
next_button.setVisibility(View.VISIBLE);
}
else
{
next_button.setVisibility(View.INVISIBLE);
}
// i just want that when it press delete image in recycelr view it should hide my button automatically.
you can use an interface to inform the fragment/activity, the list is empty.
Adapter like as below:
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {
AdapterListener listener;
public void setListener(AdapterListener listener) {
this.listener = listener;
}
...
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, final int position) {
...
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// remove your item from data base
laand_list.remove(position); // remove the item from list
notifyItemRemoved(position); // notify the adapter about the removed item
if (laand_list.size()==0)
listener.onDataListIsEmpty();
}
});
}
public interface AdapterListener {
void onDataListIsEmpty();
}
}
The Activity/Fragment like as below:
class MyActivity extends Activity implements CustomAdapter.AdapterListener {
CustomAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new CustomAdapter();
adapter.setListener(this);
...
}
#Override
public void onDataListIsEmpty() {
// set visible or gone views
}
}

how to Update ListView after deletion

Here I'm using Custom Adapter by implementing listAdapter to Support buttons in the list items. When i click the Delete button it deletes currect row. But i can't able to refresh this listView.
File Structure is MainActivity -> FragmentClass-> this Custom class for the listAdpater.
public class Category_ListView_Custom_Adapter extends BaseAdapter implements ListAdapter{
private Realm realm;
private ArrayList<String> list = new ArrayList<>();
private Context context;
public Category_ListView_Custom_Adapter(ArrayList<String> list, Context context){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View view1 = view;
realm = Realm.getDefaultInstance();
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_listview_row, null);
}
TextView listItemText = (TextView) view.findViewById(R.id.item);
listItemText.setText(list.get(i));
ImageView edit = (ImageView) view.findViewById(R.id.image);
ImageView delete = (ImageView) view.findViewById(R.id.delete);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// list.remove(i);
/// Toast.makeText(view.getContext(), "hey "+list.get(i).toString(), Toast.LENGTH_SHORT).show();
// notifyDataSetChanged();
Intent intent = new Intent(context, AddCategory.class);
intent.putExtra("category","expense");
intent.putExtra("subcategory", list.get(i));
context.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RealmResults<Category> categorylist = realm.where(Category.class).equalTo("Id",i+1).and().equalTo("Subcategory",list.get(i)).findAll();
for (Category category : categorylist) {
realm.beginTransaction();
categorylist.deleteFirstFromRealm();
realm.commitTransaction();
try {
context.notifyAll();
}catch (Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
// Expense.call_resume
}
}
});
return view;
}
}
Please Help me. Thank you.
You are .removing from a wrong view. Try to make root List<> static and do Class.list.get(i).remove or something like that.
Also, try to hide a view inside your get view.

Deleting Room entry from RecyclerView

I am new to programming and I followed this tutorial to create a RecyclerView making use of an adapter. I have no idea how to use the delete function from my Dao in relation to the ImageButton. I have next to each entry. Also, this is my first app, so please be gracious when you see things like ".allowMainThreadQueries".
Activity with recyclerview:
public class DatabaseActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
FloatingActionButton fab;
ImageButton delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
recyclerView = findViewById(R.id.recycler_view);
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "production").allowMainThreadQueries().build();
final List<Student> students = db.studentDao().getAllUsers();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new StudentAdapter(students);
recyclerView.setAdapter(adapter);
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DatabaseActivity.this, DatabaseAddActivity.class));
}
});
}
}
Adapter:
class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {
List<Student> students;
public StudentAdapter(List<Student> students) {
this.students = students;
}
#Override
public StudentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(StudentAdapter.ViewHolder holder, int position) {
holder.first_name.setText(students.get(position).getFirstName());
holder.last_name.setText(students.get(position).getLastName());
holder.email.setText(students.get(position).getEmail());
}
//See how many items need to be displayed
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView first_name;
public TextView last_name;
public TextView email;
public ImageButton delete;
//What we are showing in the viewholder
public ViewHolder(View itemView) {
super(itemView);
first_name = itemView.findViewById(R.id.first_name);
last_name = itemView.findViewById(R.id.last_name);
email = itemView.findViewById(R.id.email);
delete = itemView.findViewById(R.id.delete);
}
}
}
Dao:
#Dao
public interface StudentDao {
#Query("SELECT * FROM student ")
List<Student> getAllUsers();
#Query("SELECT * FROM student WHERE monday = 1")
List<Student> getMonday();
#Query("SELECT * FROM student WHERE tuesday = 1")
List<Student> getTuesday();
#Query("SELECT * FROM student WHERE wednesday = 1")
List<Student> getWednesday();
#Query("SELECT * FROM student WHERE thursday = 1")
List<Student> getThursday();
#Query("SELECT * FROM student WHERE friday = 1")
List<Student> getFriday();
#Insert
void insertAll(Student... students);
#Delete
void delete(Student student);
#Update
void updateStudent(Student student);
}
Student Add:
public class DatabaseAddActivity extends AppCompatActivity {
//Calling needed resources
EditText firstName;
EditText lastName;
EditText email;
Button button;
CheckBox monday, tuesday, wednesday, thursday, friday;
//Defining which view.xml file to use
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_add);
//Using resources to find using .xml setup
firstName = findViewById(R.id.first_name);
lastName = findViewById(R.id.last_name);
email = findViewById(R.id.email);
monday = findViewById(R.id.monday_switch);
tuesday = findViewById(R.id.tuesday_switch);
wednesday = findViewById(R.id.wednesday_switch);
thursday = findViewById(R.id.thursday_switch);
friday = findViewById(R.id.friday_switch);
button = findViewById(R.id.button_add);
//What happens when button is pressed
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "production").allowMainThreadQueries().build();
Boolean mondayState = monday.isChecked();
Boolean tuesdayState = tuesday.isChecked();
Boolean wednesdayState = wednesday.isChecked();
Boolean thursdayState = thursday.isChecked();
Boolean fridayState = friday.isChecked();
Student student = new Student(firstName.getText().toString(), lastName.getText().toString(), email.getText().toString(), mondayState, tuesdayState, wednesdayState, thursdayState, fridayState);
db.studentDao().insertAll(student);
startActivity(new Intent(DatabaseAddActivity.this,DatabaseActivity.class));
}
});
}
}
In DatabaseActivity:
adapter = new StudentAdapter(db, students);
UPDATED
In your Adapter class:
AppDatabase db;
List<Student> students;
public StudentAdapter(AppDatabase db, List<Student> students) {
this.db = db;
this.students = students;
}
#Override
public void onBindViewHolder(StudentAdapter.ViewHolder holder, int position) {
Student student = students.get(position);
holder.first_name.setText(students.get(position).getFirstName());
holder.last_name.setText(students.get(position).getLastName());
holder.email.setText(students.get(position).getEmail());
holder.delete.setOnClickListener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.delete(student);
students.remove(student);
notifyItemRemoved(position);
}
});
}

How to destroy activity without crashing the app

I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?

Resources