package lab.ex1;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import lab.ex1.HospitalDatabase.Patient;
public class DisplayPatient extends HospitalActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
displayData();
}
private void displayData()
{
final List<Integer> myList = new ArrayList<Integer>();
final Intent me = new Intent(DisplayPatient.this,UpdatePatient.class);
final Bundle b = new Bundle();
//Build new Patient
PatientData build = new PatientData();
final TableLayout viewData = (TableLayout)findViewById(R.id.tblDisplay);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Patient.patientTableName);
SQLiteDatabase db = mDatabase.getReadableDatabase();
String asColumnsToReturn[] = {Patient.patientTableName + "." + Patient.ID,
Patient.patientTableName + "." + Patient.firstName,
Patient.patientTableName + "." + Patient.lastName,
Patient.patientTableName + "." + Patient.room,
Patient.patientTableName + "." + Patient.department};
Cursor c = queryBuilder.query(db,asColumnsToReturn,null,null,null,null,Patient.DEFAULT_SORT_ORDER);
if (c.moveToFirst())
{
for (int i=0; i< c.getCount(); i++)
{
final TableRow newRow = new TableRow(this);
Button update = new Button(this);
TextView display = new TextView(this);
display.setTextSize(15);
update.setX(15);
update.setY(10);
update.setTextSize(10);
Button deleteButton = new Button(this);
deleteButton.setX(100);
deleteButton.setY(100);
deleteButton.setTextSize(10);
deleteButton.setText("Delete");
update.setText("Update");
deleteButton.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
update.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
newRow.setTag(c.getInt(c.getColumnIndex(Patient.ID))); // set the tag field on the TableRow view so we know which row to delete
myList.add(c.getInt(c.getColumnIndex(Patient.ID)));
build.setID(Integer.parseInt(c.getString(c.getColumnIndex((Patient.ID)))));
build.setFirstName((c.getString(c.getColumnIndex(Patient.firstName))));
build.setLastName(c.getString(c.getColumnIndex(Patient.lastName)));
build.setDepartment(c.getString(c.getColumnIndex(Patient.department)));
build.setRoom(Integer.parseInt(c.getString(c.getColumnIndex(Patient.room))));
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer id = (Integer) v.getTag();
deletePatient(id);
final TableLayout patientTable = (TableLayout) findViewById(R.id.tblDisplay);
View viewToDelete = patientTable.findViewWithTag(id);
viewData.removeView(viewToDelete);
}
});
update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = (Integer)v.getTag();
final TableLayout patientRmv = (TableLayout)findViewById(R.id.tblDisplay);
for (Integer delete : myList )
{
View viewToDelete = patientRmv.findViewWithTag(delete);
viewData.removeView(viewToDelete);
}
b.putString("key", Integer.toString(id));
me.putExtras(b);
startActivity(me);
}
});
display.setText(build.toString());
newRow.addView(display);
newRow.addView(update);
//newRow.addView(deleteButton);
viewData.addView(newRow);
c.moveToNext();
}
}
else
{
TableRow newRow = new TableRow(this);
TextView noResults = new TextView(this);
noResults.setText("No results to show.");
newRow.addView(noResults);
viewData.addView(newRow);
}
c.close();
db.close();
}
public void deletePatient(Integer id)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
String astrArgs[] = { id.toString() };
db.delete(Patient.patientTableName, Patient.ID+ "=?",astrArgs );
db.close();
}
}
package lab.ex1;
import lab.ex1.HospitalDatabase.Patient;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class UpdatePatient extends HospitalActivity {
Spinner spinner;
TextView update;
String up;
Button check;
EditText entry;
String setPosition;
TextView updateID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatepatient);
check = (Button)findViewById(R.id.btnUpdate);
entry = (EditText)findViewById(R.id.editUpdate);
updateID = (TextView)findViewById(R.id.txtIDUpdate);
Bundle accept = getIntent().getExtras();
up = accept.getString("key","0");
updateID.setText(null);
updateID.setText("ID: " + up);
update = (TextView)findViewById(R.id.txtUpdateMessage);
update.setText(null);
// update.setText(up);
spinner = (Spinner) findViewById(R.id.spnChoice);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.arrFields, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateDB(entry.getText().toString(),setPosition,up);
}
});
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
update.setText(null);
update.setText("I will update On " + adapterView.getItemAtPosition(pos).toString());
setPosition = adapterView.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void updateDB(String valuesToUpdate, String field,String ID)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
db.beginTransaction();
try
{
ContentValues updatePatient = new ContentValues();
if (field == "First Name")
{
updatePatient.put(Patient.firstName, valuesToUpdate);
String astrArgs[] = { up.toString() };
db.update(Patient.patientTableName,updatePatient, Patient.ID+"=?", astrArgs);
//
db.setTransactionSuccessful();
}
}
finally
{
db.endTransaction();
}
db.close();
Intent me = new Intent(UpdatePatient.this,DisplayPatient.class);
startActivity(me);
}
}
I am using Android SQLite Database. In my display class, it reads all the entries from the database and displays them along with an update button next to each entry. That entries update button's tag has entries Patient.ID. When the user clicks update, they are taken to the update class where they can select what they want to update, First Name, Last Name, Apartment, Room. Afterward they click update, to which they are taken back to the Display class and they should see there changes. However, when they are taken back, the previous value is still there, the changes do not show up, what am I missing?
Move your displaydata() call from onCreate to onResume.
Related
I wanna ask regarding this recycleview issues, my code doesnt show any problem,but why my recycleview output became like this RecycleView Output. I had tried by change switch case() to if else() but it will give error if I write throw new IllegalStateException("Unexpected value:" + data.getItem()); at the end of else. The app will crash and stop running if I did not commend the exception. When I still using switch case, it will came out an error of NullException
This is my code:
MainActivity() code
package com.example.assignment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button AddBtn;
private Button signOutBtn;
private RecyclerView recyclerView;
private FirebaseAuth auth;
private DatabaseReference ref;
private String userID = "";
private ProgressDialog progressDialog;
private ItemsAdapter itemsAdapter;
private ArrayList<Data> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
textView=findViewById(R.id.totalAmount);
AddBtn = findViewById(R.id.add_new);
auth = FirebaseAuth.getInstance();
userID = auth.getCurrentUser().getUid();
ref = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
progressDialog = new ProgressDialog(this);
AddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItem();
}
});
recyclerView =findViewById(R.id.recycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
dataList = new ArrayList<>();
itemsAdapter = new ItemsAdapter(MainActivity.this, dataList);
recyclerView.setAdapter(itemsAdapter);
readItems();
// signOutBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// FirebaseAuth.getInstance().signOut();
// }
// });
}
private void readItems(){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
Query query = databaseReference.orderByChild("date").equalTo(date);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
dataList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Data data = snapshot.getValue(Data.class);
dataList.add(data);
}
itemsAdapter.notifyDataSetChanged();
int totalAmount = 0;
for(DataSnapshot ds : snapshot.getChildren()){
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object total = map.get("amount");
int getTotal = Integer.parseInt(String.valueOf(total));
totalAmount+=getTotal;
textView.setText("Total Spending : RM" + totalAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void addItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//LayoutInflater layout = LayoutInflater.from(this);
LayoutInflater layout = getLayoutInflater();
View view = layout.inflate(R.layout.input_layout, (ViewGroup)findViewById(R.id.inputLayout));
setContentView(view);
final AlertDialog dialog = alert.create();
dialog.setCancelable(false);
final Spinner spinnerItem = view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.category));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerItem.setAdapter(adapter);
final EditText amount = view.findViewById(R.id.insert_amount);
final EditText notes = view.findViewById(R.id.insert_note);
final Button saveButton = view.findViewById(R.id.add_button);
final Button cancelButton = view.findViewById(R.id.cancel_button);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountGet = amount.getText().toString();
String notesGet = notes.getText().toString();
String categoryGet = spinnerItem.getSelectedItem().toString();
Drawable icon = getResources().getDrawable(R.drawable.error);
if(amountGet.isEmpty()){
amount.setError("Please enter an amount!!!", icon );
return;
}
if(notesGet.isEmpty()){
notes.setError("Please enter a notes!!!", icon );
return;
}
if(categoryGet.equals("Select a Category")){
Toast.makeText(MainActivity.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Had added the information into database");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
String id = ref.push().getKey();
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
Data inform = new Data(categoryGet, date, id, notesGet, Integer.parseInt(amountGet));
ref.child(id).setValue(inform).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Information added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Fail to add the information", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
}
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
dialog.dismiss();
}
});
}
}
ItemsAdapter() code
package com.example.assignment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.viewHolder> {
private Context context;
private List<Data> dataList;
public ItemsAdapter(Context context, List<Data> data) {
this.context = context;
this.dataList = data;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.output_layout, parent, false);
//return new ItemsAdapter.viewHolder(view);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
final Data data = dataList.get(position);
holder.category.setText("Category :" + data.getItem());
holder.amount.setText("Amount :" + data.getAmount());
holder.date.setText("Date :" + data.getDate());
holder.notes.setText("Note :" + data.getNotes());
// switch(data.getItem()){
//
// case "Petrol Spend":
// holder.imageView.setImageResource(R.drawable.petrol);
// break;
//
// case "Groceries Spend":
// holder.imageView.setImageResource(R.drawable.grocery);
// break;
//
// case "eWallet Transaction":
// holder.imageView.setImageResource(R.drawable.wallet);
// break;
//
// case "Other Eligible Spend":
// holder.imageView.setImageResource(R.drawable.spend);
// break;
//
// default:
// throw new IllegalStateException("Unexpected value:" + data.getItem());
// }
if(data.getItem() == "Petrol Spend"){
holder.imageView.setImageResource(R.drawable.petrol);
}else if(data.getItem() == "Groceries Spend"){
holder.imageView.setImageResource(R.drawable.grocery);
}else if(data.getItem() == "eWallet Transaction"){
holder.imageView.setImageResource(R.drawable.wallet);
}else if(data.getItem() == "Other Eligible Spend"){
holder.imageView.setImageResource(R.drawable.spend);
}
//else throw new IllegalStateException("Unexpected value:" + data.getItem());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
public TextView category, amount, date, notes;
public ImageView imageView;
public viewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category);
amount = itemView.findViewById(R.id.amount);
date = itemView.findViewById(R.id.date);
notes = itemView.findViewById(R.id.note);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Instead of :
dataList.add(data);
itemsAdapter.notifyDataSetChanged();
Try this:
// add this in the place of dataList.add(data)
adapter.setDataList(data);
// Add this setter inside the adapter;
setDataList(List<Data> datalist){
this.dataList = dataList;
notifyItemChanged(0,dataList);
}
in my recycler view , when data get added , recycelr view does not show it until user close the activity and open it another time.
I think it has something to do with notifydataetchanger.
please help me with this
the only thing that worked by now was to creating an Intent .
but it makes app to loob very bad
my adaptor
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Rec_adaptor_aza extends RecyclerView.Adapter<Rec_adaptor_aza.ViewHolder> {
Context context;
public Rec_adaptor_aza(Context context, List<Model_aza> list_aza) {
this.context = context;
this.list_aza = list_aza;
}
List<Model_aza> list_aza;
#NonNull
#Override
public Rec_adaptor_aza.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.rec_row_aza,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Rec_adaptor_aza.ViewHolder holder, int position) {
Model_aza modelAza =list_aza.get(position);
holder.txt_name.setText(modelAza.getName_aza());
holder.txt_semat.setText(modelAza.getSemat_aza());
holder.txt_saat_voood.setText(modelAza.getSaaat_vorood_aza());
holder.txt_saat_khoroo.setText(modelAza.getSaat_khorooj_aza());
}
#Override
public int getItemCount() {
return list_aza.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name,txt_semat,txt_saat_voood,txt_saat_khoroo;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txt_name=itemView.findViewById(R.id.txt__person__name);
txt_semat=itemView.findViewById(R.id.txt__person__semat);
txt_saat_voood=itemView.findViewById(R.id.txt__person__enter);
txt_saat_khoroo=itemView.findViewById(R.id.txt__person__out);
}
}
}
my model class
package com.example.myapplication;
public class Model_aza {
private String name_aza;
private String semat_aza;
private String saaat_vorood_aza;
public String getName_aza() {
return name_aza;
}
public void setName_aza(String name_aza) {
this.name_aza = name_aza;
}
public String getSemat_aza() {
return semat_aza;
}
public void setSemat_aza(String semat_aza) {
this.semat_aza = semat_aza;
}
public String getSaaat_vorood_aza() {
return saaat_vorood_aza;
}
public void setSaaat_vorood_aza(String saaat_vorood_aza) {
this.saaat_vorood_aza = saaat_vorood_aza;
}
public String getSaat_khorooj_aza() {
return saat_khorooj_aza;
}
public void setSaat_khorooj_aza(String saat_khorooj_aza) {
this.saat_khorooj_aza = saat_khorooj_aza;
}
private String saat_khorooj_aza;
}
My activity
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Activity_Gozaresh_giri extends AppCompatActivity {
private static final String TAG = "gozaresh_activity";
List<Model_aza> list_aza;
Rec_adaptor_aza rec_adaptor_aza;
public static Context context;
SQLiteDatabase sqLiteDatabase;
ImageButton btn__add__field, btn__add__field1;
final DataBase_aza dataBase_aza = new DataBase_aza(this);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
my data base
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DataBase_aza extends SQLiteOpenHelper {
public DataBase_aza(#Nullable Context context) {
super(context, "datbase_aza", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table if not exists database_aza (_id integer primary key autoincrement,_name varcher(55) not null,_semat varcher(55) not null, _vorood varcher(6) not null, _khorooj varchar(22) not null, id__item__gozaresh integer(55))");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert_info(String name, String semat, String vorood, String khorooj, int id) {
ContentValues cv = new ContentValues();
cv.put("_name", name);
cv.put("_semat", semat);
cv.put("_vorood", vorood);
cv.put("_khorooj", khorooj);
cv.put("id__item__gozaresh", id);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.insert("database_aza", null, cv);
}
public Cursor cursor(int id) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM database_aza where id__item__gozaresh="+id, null);
}
}
I want recycler view to show data as soon as user clicks on add button
after adding entry just notify data set changed to adapter like below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
rec_adaptor_aza = new Rec_adaptor_aza(this, list_aza);
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(rec_adaptor_aza);
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
rec_adaptor_aza.notifyDataSetChanged();
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
rec_adaptor_aza.notifyDataSetChanged(); // change here
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
}
Use it like below:-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Rec_adaptor_aza adapter = new Rec_adaptor_aza(this, list_aza); // Add
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(adapter);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Model_aza modelAza = new Model_aza(); // Add
modelAza.setName_aza(name_aza);// Add
modelAza.setSemat_aza(semat_aza);// Add
modelAza.setSaaat_vorood_aza(saat_vorood_aza);// Add
modelAza.setSaat_khorooj_aza(saat_khorooj_aza);// Add
list_aza.add(modelAza);// Add
adapter.notifyDataSetChanged();// Add
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
adapter.notifyDataSetChanged();// Add
}
Just add the below code, in your clickListner, you need to add the same object in your list, and after adding you need to notify the adapter about the inserted item, by using notifyDataSetChanged().
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
/*
* Adding entered data in list*/
Model_aza mm=new Model_aza();
mm.setName_aza(name_aza);
mm.setSemat_aza(semat_aza);
mm.setSaaat_vorood_aza(saat_vorood_aza);
mm.setSaat_khorooj_aza(saat_khorooj_aza);
list_aza.add(mm);
rec_adaptor_aza.notifyDataSetChanged();
}
});
Set layoutmanager before set the adapter to recylerview in your activity, like below
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
// set layout manager before set adapter
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
I developed a word app that contains English vocabularies and users can add their favorite word by clicking on a floating button. Every time my favorite list has at list one item it is updated but when it's empty it doesn't show anything but when I run app again list updates.
if you need any code let me know to send it .
UPDATE:
Inner page :
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
Update 2:
package farmani.com.essentialwordsforielts.mainPage;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import farmani.com.essentialwordsforielts.R;
public class PageFragment extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
if (mPage == 1) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
AdapterList adapter = new AdapterList(MainActivity.context);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
if (mPage == 2) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
adapterFav = new AdapterFav(MainActivity.context);
recyclerView.setAdapter(adapterFav);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
return view;
}
#Override
public void onResume() {
super.onResume();
if (adapterFav != null){
adapterFav.notifyDataSetChanged();
}
}
}
Update 3 :AdapterFav
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
Update 4: MainActivity
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
" storage permissions are required to copy database", new Permissions.Options()
.setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
new PermissionHandler() {
#Override
public void onGranted() {
setupDB();
selectList();
selectFavorite();
}
});
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}else if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
MainActivity.this.startActivity(intent);
} else if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
if (!list.isEmpty()){
list.clear();
selectList();
} if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
}
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
Update 5 innerpage activity
package farmani.com.essentialwordsforielts.innerpage;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.mainPage.AdapterFav;
public class ActivityInnerPage extends AppCompatActivity {
private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_page);
final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
int layoutId = Integer.parseInt(extras.getString("id"));
String pageName = extras.getString("name");
assert pageName != null;
if (pageName.equals("list")) {
id = MainActivity.list.get(layoutId).getId();
word = MainActivity.list.get(layoutId).getWord();
definition = MainActivity.list.get(layoutId).getDefinition();
trans = MainActivity.list.get(layoutId).getTrans();
img = MainActivity.list.get(layoutId).getImg();
} else if (pageName.equals("favorite")) {
id = MainActivity.favorite.get(layoutId).getId();
word = MainActivity.favorite.get(layoutId).getWord();
definition = MainActivity.favorite.get(layoutId).getDefinition();
trans = MainActivity.favorite.get(layoutId).getTrans();
img = MainActivity.favorite.get(layoutId).getImg();
}
}
contentDescriptione = findViewById(R.id.content_description);
moreDescriptione = findViewById(R.id.more_description);
imgCopy = findViewById(R.id.img_copy);
imgShare = findViewById(R.id.img_share);
imgSms = findViewById(R.id.img_sms);
imgGmail = findViewById(R.id.img_gmail);
avatar = findViewById(R.id.avatar);
favorite = findViewById(R.id.favorite);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.getExpandedTitleMarginStart();
collapsingToolbarLayout.setTitle(word);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));
contentDescriptione.setText(definition);
moreDescriptione.setText(trans);
int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
avatar.setImageResource(imgageId);
SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
int value = prefes.getInt("fontsize", 16);
contentDescriptione.setTextSize(value);
moreDescriptione.setTextSize(value);
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
imgCopy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ClipboardManager clipboardManager =
(ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText(word, trans+definition);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clip);
Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
}
});
imgShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
imgGmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO
, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
imgSms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent sendSms = new Intent(Intent.ACTION_VIEW);
sendSms.putExtra("sms_body", definition + trans);
sendSms.setType("vnd.android-dir/mms-sms");
startActivity(sendSms);
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
}
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
}
In your FloatingActionButton onClick method after you save the new item in your database, insert your new item into your recyclerview datasource list and call notifyDatasetChanged() on the adapter.
Choice 1: in onResume() stub of MainActivity, call selectList() and selectFavorite() and then load the PageFragment again so that the new list is loaded properly.
This is the shortest wayout but this approach is very much unoptimized and is not recommended.
Choice 2: You will have to insert the new item in database as well as add it to the List and then call notifyDatasetChanged
In MainActivity within methods selectList() and selectFavorite() after you perform list.add(struct) and favourite.add(struct) respectively, you will have to call notifyDatasetChanged() for the Adapter.
But the problem is your RecyclerView is in the PageFragment whereas you're populating the list in MainActivity.
So move your selectList() and selectFavorite() to PageFragment where you first initialize the RecylerView then, set the Adapter and then populate the list and finally call notifyDatasetChanged() on your adapters.
i'm trying to get value from 2nd column in the database and put it into textview by clicking listview item.
DBConnection class
package com.prodev;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by Dev_Mohamed_Sayed on 7/21/2017.
*/
public class DBConnection extends SQLiteOpenHelper {
public static final String DbName="azkar.db";
public static final int Version=1;
public DBConnection(Context context){
super(context,DbName,null,Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS azkar_main ( ID INTEGER, Name TEXT, Number INTEGER, PRIMARY KEY(ID) )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS azkar_main");
onCreate(db);
}
public void InsertRowAdmin(String Name,Integer Number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Name", Name);
contentValues.put("Number", Number);
db.insert("azkar_main", null, contentValues);
}
public ArrayList getAllRecord2(){
ArrayList array_list2 = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from azkar_main", null);
res.moveToFirst();
while (res.isAfterLast() == false){
array_list2.add(res.getString(res.getColumnIndex("ID"))+ " - " + res.getString(res.getColumnIndex("Name"))+ " .. " + res.getString(res.getColumnIndex("Number")));
res.moveToNext();
}
return array_list2;
}
public void delete(Integer ID){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from azkar_main where ID="+ Integer.toString(ID));
}
}
and here is my Acivity where we should work in.
package com.prodev;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.R.layout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import java.util.ArrayList;
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_list);
DBConnection db = new DBConnection(this);
ListView ls =(ListView)findViewById(R.id.ls);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
ListView lv = (ListView) findViewById(R.id.ls);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
startActivity(i);
ListView lv = (ListView) findViewById(R.id.ls);
TextView tv = (TextView) findViewById(R.id.textView);
// The Missing Part
}
});
}
public void btn_save(View view){
EditText editText =(EditText)findViewById(R.id.editText);
ListView ls =(ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.InsertRowAdmin(editText.getText().toString(), 0);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
editText.setText("");
}
public void btn_delete(View view){
EditText txt = (EditText)findViewById(R.id.del);
ListView ls = (ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.delete(Integer.parseInt(txt.getText().toString()));
ArrayList<String> arrlist=db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
txt.setText("");
}
}
MainActivity
package com.prodev;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crash.FirebaseCrash;
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
FirebaseCrash.log("Activity created");
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_azkar:
Intent i = new Intent(MainActivity.this, ListActivity.class);
startActivity(i);
break;
case R.id.action_settings:
break;
default:
break;
}
return true;
}
}
Also i want to save number from variable will be declared later into database col Number..
i don't know how but i'll worry about that later..
On you list item click event,
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
i.putExtra("keyText","value to be passed!");
startActivity(i);
}
and in you main activity,
Intent i = getIntent();
String text = i.getStringExtra("keyText");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(text);
i have a Activity Called "SecondActivity" below is full code
package br.exemplosqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import org.w3c.dom.Text;
public class SecondActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//referencia a Spinner
//Spinner coligada;
//final TextView nome = (TextView)findViewById(R.id.txvNome);
//final TextView sobrenome = (TextView)findViewById(R.id.txvSobrenome);
//final Spinner pday = (Spinner)findViewById(R.id.spinner);
final Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
//spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter adaptercoligada = ArrayAdapter.createFromResource(this, R.array.coligada, android.R.layout.simple_spinner_item);
spcoligada.setAdapter(adaptercoligada);
Button ok = (Button)findViewById(R.id.btnok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//chamada para a nova Activity
Intent intent = new Intent(SecondActivity.this, ListUsersActivity.class);
intent.putExtra("coligada", spcoligada.getSelectedItem().toString());
//intent.putExtra("nomePessoa", nome.getText().toString());
//intent.putExtra("sobrenomePessoa", sobrenome.getText().toString());
//intent.putExtra("day", pday.getSelectedItem().toString());
startActivity(intent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
But , what i really want is , pass the item selected on Spinner , go to my BD.class on query , below is my "BD.class"
package br.exemplosqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract;
import android.widget.Spinner;
public class BD {
private SQLiteDatabase bd;
public BD(Context context){
BDCore auxBd = new BDCore(context);
bd = auxBd.getWritableDatabase();
}
public void inserir(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.insert("produtos2", null, valores);
}
public void atualizar(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.update("produtos2", valores, "_id = ?", new String[]{""+produtos.getId()});
}
public void deletar(Produtos produtos){
bd.delete("produtos2", "_id = "+produtos.getId(), null);
}
public List<Produtos> buscar(){
List<Produtos> list = new ArrayList<Produtos>();
String[] colunas = new String[]{"_id", "item", "coligada","filial"};
Cursor cursor = bd.rawQuery("select * from produtos2",null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
do {
Produtos p = new Produtos();
p.setId(cursor.getLong(0));
p.setItem(cursor.getString(1));
p.setColigada(cursor.getString(2));
p.setFilial(cursor.getString(3));
list.add(p);
} while(cursor.moveToNext());
}
return(list);
}
}
so , i want change this : Cursor cursor = bd.rawQuery("select * from produtos2",null);
to this :
Cursor cursor = bd.rawQuery("select * from "+itemselected,null);
That is the code for your solution.
Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
private static final String itemSelected=spcoligada.getSelectedItem();
Cursor cursor = bd.query(itemSelected, new String[]{ColumnName1, ColumnName2, Column2,ColumnName3,ColumnName4},
null, null, null, null, null);
I have found the Solution.
I create a class Global , and after this i assing the value of global variable to my Spiner on Select .