How to turn this activity into a fragment? - java

I am working on a sql listview , however I want to display the listview which is in an activity class (CountryListActivity.java) as a fragment in a tablayout . dbManager=newDBManager(this) gives an error when I change it to getActivity , how do I fix this?
package com.trinitytabnavigationdrawer;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class CountryListActivity extends ActionBarActivity {
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from = new String[] {
DatabaseHelper._ID,
DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
final int[] to = new int[] {
R.id.id, R.id.title, R.id.desc
};
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// OnCLickListiner For List Items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {#
Override
public void onItemClick(AdapterView <? > parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_record) {
Intent add_mem = new Intent(this, AddCountryActivity.class);
startActivity(add_mem);
}
return super.onOptionsItemSelected(item);
}
}
And the database manager class is as follows :
package com.trinitytabnavigationdrawer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c) {
context = c;
}
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
public Cursor fetch() {
String[] columns = new String[] {
DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
return i;
}
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
Please I have no clue what else to do ! Been trying for a week now , sorry I'm not good at this , just following some tutorials ! :(

Initialize the dbManager and other objects which require context inside onAttach (Context context) rather than onCreateView() method of Fragment.

Related

recycler view does not refresh and show data

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));

Android Sqlite can't get records from Listview

I am writing a program that saves to DB and then get infos from the DB using SQLiteOpenHelper.
Problem is I insert text from the edit text but I got nothing to show.
is the problem from the listview? cuz I extend from ArrayAdapter class not from enter code hereCursor adapter? or there is something wrong with my code. Please take a look at my code this is my main Acitvity
package com.perfectapps.fasaven.dbnews;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import DBHelper.DBContract;
import DBHelper.DBModel;
import newsAdapter.NewsMainMenuAdapter;
public class MainActivity extends AppCompatActivity {
Button submitNews;
ListView newsListView;
ArrayList<DBModel> dbmodel = new ArrayList<DBModel>();
EditText titleEditText;
TextView tvTitle;
TextView tvInfo;
EditText infoEditText;
DBContract dbContract;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTitle =(TextView)findViewById(R.id.tvTitle);
tvInfo =(TextView)findViewById(R.id.tvInfo);
submitNews = (Button)findViewById(R.id.submit_news);
newsListView = (ListView)findViewById(R.id.lvNews);
titleEditText = (EditText)findViewById(R.id.etNews);
infoEditText = (EditText)findViewById(R.id.etNewsInfo);
dbContract = new DBContract(this,null,null,1);
NewsMainMenuAdapter customeAdapter = new NewsMainMenuAdapter(getApplicationContext(), R.layout.row_news_element,dbmodel);
newsListView.setAdapter(customeAdapter);
// printDataBase();
submitNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBModel dbModel = new DBModel();
dbModel.setNewsInfos(infoEditText.getText().toString());
dbModel.setNewsTitle(titleEditText.getText().toString());
dbContract.addNews(dbModel);
Toast.makeText(getApplicationContext(),"saved to DB", Toast.LENGTH_LONG ).show();
titleEditText.setText("");
infoEditText.setText("");
// printDataBase();
}
});
}
public void printDataBase(){
DBModel dbModel = new DBModel();
String dbToStringTitle = dbContract.readNewsTitle();
tvTitle.setText(dbToStringTitle);
titleEditText.setText("");
String dbToStringInfo =dbContract.readNewsInfo();
tvInfo.setText(dbToStringInfo);
infoEditText.setText("");
}
}
This is my custom Adapter
package newsAdapter;
import android.support.annotation.LayoutRes;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import DBHelper.*;
import com.perfectapps.fasaven.dbnews.*;
import java.util.ArrayList;
/**
* Created by Salem on 22/12/2017.
*/
public class NewsMainMenuAdapter extends ArrayAdapter{
Context context;
ArrayList<DBModel> newsData;
int resource;
public NewsMainMenuAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<DBModel> newsData) {
super(context, resource, newsData);
this.context =context;
this.newsData = newsData;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_news_element,null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvInfo = (TextView)convertView.findViewById(R.id.tvInfo);
viewHolder.tvTitle = (TextView)convertView.findViewById(R.id.tvTitle);
viewHolder.tvTitle.setText(newsData.get(position).getNewsTitle());
viewHolder.tvInfo.setText(newsData.get(position).getNewsInfos());
//return super.getView(position, convertView, parent);
return convertView;
}
//#Nullable
// #Override
// public DBModel getItem(int position) {
// return super.getItem(position);
//}
class ViewHolder{
TextView tvTitle;
TextView tvInfo;
}
}
Here is my DB helper
package DBHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Salem on 22/12/2017.
*/
public class DBContract extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "newsDB.db";
public static final String TABLE_NAME = "news";
public static final String COLUMN_ID = "_ID";
public static final String COLUMN_NEWS_TITLE = "newstitle";
public static final String COLUMN_NEWS_IMAGE = "newsimage";
public static final String COLUMN_NEWS_INFO= "newsinfo";
public DBContract(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_NAME, factory, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_NAME + " ("
+COLUMN_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NEWS_TITLE+ " TEXT ,"
+COLUMN_NEWS_INFO+ " TEXT );";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public void addNews(DBModel dbModel){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NEWS_TITLE, dbModel.getNewsTitle());
contentValues.put(COLUMN_NEWS_INFO, dbModel.getNewsInfos());
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
}
public String readNewsTitle(){
String readNews = "";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_TITLE+" FROM "+TABLE_NAME +" where 1";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE))!=null);
{
readNews += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE));
readNews +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNews;
}
public String readNewsInfo(){
String readNewsInfo="";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_INFO+" FROM "+TABLE_NAME ;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO))!=null);
{
readNewsInfo += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO));
readNewsInfo +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNewsInfo;
}
}
There is one 4th class that has setters and getters named DBModel
and got XML for main activity which has listview.. but it when I input from edit text it doesn't show there

data in the row is not deleted from table

when I click delete it doesn't delete or edit the row I created
so my MainActivity is
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col1;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col2;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
FloatingActionButton fab;
DatabaseHelper mydb;
ListView listView;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb =new DatabaseHelper(this);
fab= (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(this);
ListView listView = (ListView)findViewById(R.id.list);
registerForContextMenu(listView);
}
#Override
public void onResume() {
super.onResume();
ArrayList<String> theList =new ArrayList<>();
Cursor data= mydb.getAllData();
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(null);
if (data.getCount()==0){
Toast.makeText(MainActivity.this,"data not inserted",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// int count= mydb.updaterow(getString(col2),EditText.)
return true;
case R.id.delete:
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
My DataBasehelper class
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by BHUSHAN on 24-08-2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";
//DatabaseHelper mydb;
public DatabaseHelper(Context context) {
super(context, Database_Name, null, 1);
//mydb=new DatabaseHelper(context);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + Table_Name);
onCreate(db);
}
public boolean insertData(String data, String Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, Data);
long result = db.insert(Table_Name, null, contentValues);
if (result==-1)
return false;
else
return true;
}
public ArrayList<String> getList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.query(Table_Name,new String[]{col1},new String(col2),null,null,null,null);
while (cursor.moveToNext()){
int index= cursor.getColumnIndex(col1);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
return res;
}
public int deleterow(String col1) {
String whereClause = "ID = ?";
String[] whereArgs = {String.valueOf(col1)};
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(Table_Name, whereClause, whereArgs);
db.close();
return count;
}
/* public int updaterow(String oldname, String newdata){
SQLiteDatabase db= mydb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.col2,newdata);
String[] whereargs={oldname};
int count = db.update(Table_Name,cv, DatabaseHelper.col2+"=?" , whereargs);
return count;
}*/
}
my Main2Activity class where I edit and insert data
package com.frolicfreak.bhushan.memo;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db;
EditText Data;
FloatingActionButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
db = new DatabaseHelper(this);
Data = (EditText)findViewById(R.id.edit);
add =(FloatingActionButton)findViewById(R.id.add);
AddData();
}
public void AddData(){
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
db.insertData(Data.getText().toString(),
Data.getText().toString() );
if (isInserted==true)
Toast.makeText(Main2Activity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"data not
inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
please help me I'm new to programming so I'm trying to learn here
thankyou in advance
and I actually need help with editing and saving the data too I wrote the code but I saved it in the comments
Your delete function is working fine according to the code. Check the return is greater than 0 or not.
But you won't be able to see the changes in the ListView because you have to populate the list again.
Set an CursorAdapter since you're using a database to link to the listview and use CursorAdapter.notifyDataSetChanged()
Or create a method that will recreate the listview when a delete occurs.
ArrayList<String> COUNTRIES = new ArrayList<>();
public void refreshView() {
MyDatabase database = new MyDatabase(ViewList.this);
Cursor cursor = database.fetchAllData();
COUNTRIES.clear();
while (cursor.moveToNext()) {
String temp = cursor.getString(cursor.getColumnIndex(database.COL1));
COUNTRIES.add(temp);
}
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
}
When deleting, you are calling this
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
You are not passing the id of selected item, but you are passing menu item's string fetched by getString(...) method, which is weird. There are so much unused code in your class.
I advice you to work on BaseAdapter and ListView.
It's not a good programming pattern to call onResume() method. You should extract it to different method and call it in onResume().
Anyway, in this case notifyDataSetChanged() is a solution what you are looking for.

get value from database column by listview item click

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);

Refresh a Loader when data is changed - android

I user LoaderManager and CursorLoader to load the data from my database using a ContentProvider.
Now, the initial load is fine. I have a ListView that display all the rows from the DB(only the names-String adapter).
Now, when I add/delete a row from the database, I want to refresh the ListView so it will display the recent changes.
Currently I just restart the loader with the method "restartLoader" whenever a change is commited but I want to ask if there is another way of doing this without restarting the loader.
Here is my activity class code:
package com.silverfix.phony.activities;
import java.util.ArrayList;
import com.silverfix.phony.R;
import com.silverfix.phony.contentprovider.PhonyContentProvider;
import com.silverfix.phony.database.RingtonesTable;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class RingtonesActivity extends Activity implements LoaderCallbacks<Cursor>{
private final int PICK_RINGTONE_CODE = 1;
private final int CURSOR_LOADER_ID = 1;
private final int EDIT_ID = 1;
private final int DELETE_ID = 2;
private String[] ContextCommands;
private ArrayAdapter<String> adapter;
private ArrayList<String> ringtones;
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
listview = (ListView) findViewById(R.id.list);
Button add = (Button) findViewById(R.id.add_ringtone);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
});
fillData();
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
switch (arg0) {
case 1: // PICK_RINGTONE_CODE
if (arg1 == RESULT_OK) {
Uri ringtoneURI = arg2.getData();
String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ringtoneURI,
projection, null, null, null);
cursor.moveToFirst();
int column = cursor
.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
String displayName = cursor.getString(column);
addRingtone(ringtoneURI, displayName);
cursor.close();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ringtones, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fillData() {
getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this);
ringtones = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ringtones);
ContextCommands = getResources().getStringArray(R.array.commands);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
editRingtone();
}
});
registerForContextMenu(listview);
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(ContextCommands[info.position]);
String[] menuItems = getResources().getStringArray(R.array.commands);
menu.add(Menu.NONE, EDIT_ID, 0, menuItems[0]);
menu.add(Menu.NONE, DELETE_ID, 0, menuItems[1]);
}
}
});
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case EDIT_ID:
editRingtone();
return true;
case DELETE_ID:
String name = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
getContentResolver().delete(PhonyContentProvider.RINGTONES_URI, RingtonesTable.COLUMN_NAME
+ "='" + name + "'", null);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void editRingtone() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
private void addRingtone(Uri uri, String name) {
String[] projection = { RingtonesTable.COLUMN_NAME };
Cursor cursor = getContentResolver().query(
PhonyContentProvider.RINGTONES_URI, projection,
RingtonesTable.COLUMN_NAME + "='"+name+"'", null, null);
if (cursor.getCount() == 0) {
ContentValues values = new ContentValues();
values.put(RingtonesTable.COLUMN_NAME, name);
values.put(RingtonesTable.COLUMN_URI, uri.toString());
getContentResolver().insert(PhonyContentProvider.RINGTONES_URI,
values);
getLoaderManager().restartLoader(CURSOR_LOADER_ID, null, this);
} else {
Toast.makeText(this, "You already picked that ringtone!",
Toast.LENGTH_LONG).show();
cursor.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {RingtonesTable.COLUMN_ID, RingtonesTable.COLUMN_NAME, RingtonesTable.COLUMN_URI};
return new CursorLoader(this, PhonyContentProvider.RINGTONES_URI, projection, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
swapCursor(null);
}
private void swapCursor(Cursor cursor) {
if(cursor != null) {
cursor.moveToFirst();
ringtones.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int column = cursor.getColumnIndex(RingtonesTable.COLUMN_NAME);
ringtones.add(cursor.getString(column));
}
adapter.notifyDataSetChanged();
cursor.close();
return;
}
ringtones.clear();
adapter.notifyDataSetChanged();
}
}
Since you already have access to the loader, you may not expect that much of a change, but another way of implementing this is by having the cursor setting PhonyContentProvider.RINGTONES_URI as its notification uri and notifying the uri whenever the database data changes.
Relevant methods:
setNotificationUri
notifyChange

Categories

Resources