ContentProvider.createUri Cannot resolve method? - java

I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method. What i am missing can anyone tell me please. Here is my code for class:
public class Connectivity extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
MySQLiteHelper db;
String[] name;
String[] username;
String[] password;
String[] category;
int[] ids;
int[] color;
ListView listView;
Cursor identityCursor;
FloatingActionButton addIndentity;
int REQUEST_CODE =0;
int color1;
ToastersAdapter customAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.cards_frag, container, false);
addIndentity = (FloatingActionButton) android.findViewById(R.id.fab3);
db = new MySQLiteHelper(getActivity());
final List<IdentityHelper> list = db.getAllIdentities();
name= new String[db.getIdentitiesCount()];
username = new String[db.getIdentitiesCount()];
password = new String[db.getIdentitiesCount()];
category = new String[db.getIdentitiesCount()];
color = new int[db.getIdentitiesCount()];
ids = new int[db.getIdentitiesCount()];
for (int i = 0; i < list.size(); i++) {
IdentityHelper n= list.get(i);
name[i]= n.getName();
username[i]=n.getUsername();
password[i]=n.getPassword();
category[i]=n.getCategory();
color[i] = n.getColor();
ids[i] = n.getId();
}
addIndentity.setOnClickListener(handler);
// Get access to the underlying writeable database
SQLiteDatabase dbs = db.getWritableDatabase();
// Query for items from the database and get a cursor back
identityCursor = dbs.rawQuery("SELECT * FROM Identities ORDER BY category", null);
listView = (ListView) android.findViewById(R.id.listView1);
customAdapter = new ToastersAdapter(getActivity(), identityCursor);
listView.setAdapter(customAdapter);
addIndentity.attachToListView(listView);
getActivity().getSupportLoaderManager().initLoader(0, null, Connectivity.this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
ToastersAdapter adapter1 = (ToastersAdapter) adapter.getAdapter();
Object sectionObject = adapter1.getItem(position);
int cursorPosition = adapter1.getCursorPositionWithoutSections(position);
if (adapter1.isSection(position) && sectionObject != null) {
// Handle the section being clicked on.
Toast.makeText(getActivity(),"Header Clicked", Toast.LENGTH_SHORT).show();
} else if (cursorPosition != SectionCursorAdapter.NO_CURSOR_POSITION) {
// Handle the cursor item being clicked on.
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("Name", name[cursorPosition]);
bundle.putString("Username",username[cursorPosition]);
bundle.putString("Password",password[cursorPosition]);
bundle.putString("Category", category[cursorPosition]);
bundle.putInt("Color", color[cursorPosition]);
bundle.putInt("ID", ids[cursorPosition]);
Intent intent = new Intent(getActivity(), theIdentity.class);
intent.putExtras(bundle);
Connectivity.this.startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
getActivity().finish();
}}
});
return android;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
**String orderBy = category[id] + " ASC, " + name[id] + " ASC";
return new CursorLoader(this, ContentProvider.createUri(IdentityHelper.class, null), null, null, null, orderBy);**
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
customAdapter.swapCursor(null);
}
I have used https://github.com/twotoasters/SectionCursorAdapter, for Cursor adapter to manipulate the ListView. I will really appreciate any help

Since there is no createUri method in android.content.ContentProvider class, it appears to me that your ContentProvider class is from some other library.
May be it is ActiveAndroid, which has createUri method in com.activeandroid.content.ContentProvider class.

I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method
There is no method named createUri() on ContentProvider, whether static or otherwise.

Related

List is returning item after deleting all the items [duplicate]

My List is returning an item after clearing all the items by deleting ,On app fresh install its returing null which is good but after adding item and then by deleting all, this happens when go back from that activity and come again, list.size() is returning 1 and an item is remaing ,i don't know if it is loading from cache object instance here is my code of adapter class
[please look to the image attached ,list is empty but still counter 1 counter = cartModelList.size()]i have a list of cart itemsprivate List<CartModel> cartModelList;
It's returning null on app fresh install which is good but when i add item to the cart and then remove all the items then its returning 1.
I mean cartmodelList.size() is returning as far I know it's returning some items from cached objects or some thing like that.
The question is how to remove that List object cached or any alternative?
I tried on delete button but still cached coming
public static double p = 0;
private List<CartModel> cartModelList;
Database db;
Context context;
public CartAdapter(Context context, List<CartModel> cartModelList) {
this.cartModelList = cartModelList;
this.context = context;
db = new Database(context);
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_layout_item, parent, false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
String namee = cartModelList.get(position).getName();
String manufacturere = cartModelList.get(position).getManufacturer();
String availabilitye = cartModelList.get(position).getAvailability();
String e_parte = cartModelList.get(position).getE_part();
String m_parte = cartModelList.get(position).getM_part();
String floatprice = cartModelList.get(position).getUnit_();
String int_quantity = cartModelList.get(position).getQuantity();
String float_line_total = cartModelList.get(position).getLine_total();
holder.setItemDetails(namee, manufacturere, availabilitye, e_parte, m_parte, floatprice, int_quantity, float_line_total);
int checker = SharedPrefManager.getInstance(context).cartcount().getCounter();
if (checker <= 0){
cartModelList.clear();
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyDataSetChanged();
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(--COUNTER_BADGE);
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return cartModelList.size();
}
class Viewholder extends RecyclerView.ViewHolder {
private TextView name;
private TextView manufacturer;
private TextView availability;
private TextView e_part;
private TextView m_part;
private TextView price;
private EditText quantity;
private TextView linetotal;
private Button btn_delete;
private Button btn_update;
private Button adapter_livestock;
public SpinKitView progressbar;
public Viewholder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
manufacturer = itemView.findViewById(R.id.manufacturer);
availability = itemView.findViewById(R.id.availability);
e_part = itemView.findViewById(R.id.e_part);
m_part = itemView.findViewById(R.id.m_part);
price = itemView.findViewById(R.id.price);
quantity = itemView.findViewById(R.id.quantity);
linetotal = itemView.findViewById(R.id.linetotal);
btn_delete = itemView.findViewById(R.id.btn_delete);
btn_update = itemView.findViewById(R.id.btn_update);
adapter_livestock = itemView.findViewById(R.id.adapter_livestock);
progressbar = itemView.findViewById(R.id.adapterrprogresslivestockprogress);
}
private void setItemDetails(String namee, String manufacturere, String availabilitye, String e_parte, String m_parte, String floatprice, String int_quantity, String float_line_total) {
name.setText(namee);
manufacturer.setText(manufacturere);
availability.setText(availabilitye);
e_part.setText(e_parte);
m_part.setText(m_parte);
price.setText("£"+floatprice);
quantity.setText(int_quantity);
linetotal.setText("£"+float_line_total);
}
}
[https://i.stack.imgur.com/PxDTZ.jpg]
Okay... The first.
if (db.deleteProduct(cartModelList.get(position).getID()))
will not delete your item from cartModelList, you need to do it manually. Like this:
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position)
And the second. You have to call notifyDataSetChanged() or itemChanged or itemRemoved etc. only in the end of your deletion method. Please, tell me, if it worked.
P.S. Your items do not cached. The problem is in your code order.
Edit 1. Also, you need to check your db.deleteProduct method. Is it worked? Is your if statement worked?
Edit 2. Try this.
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(cartModelList.size());
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
my problem is solved by putting cartModelList.clear on delete button when cartModelList.size() == 1 , so after deleting the last item it will clear the list.

How to refresh List Adapter from another class?

I wonder if anybody could help me with my code. I have a ListView which lists Devices from database. Each device has a status which is represented with colored icon. Each device has also bunch of buttons to start/stop/etc the device and that works (after logout and login icon changed color). What I want to do is somehow refresh this list so icons color is up-to-date. Thanks in advance!
ListAdapter.java:
public class ListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] deviceName;
private final String[] ip;
private final Integer[] imgid;
public ListAdapter(Activity context, String[] deviceName, String[] ip, Integer[] imgid) {
super(context, R.layout.list_item, deviceName);
this.context = context;
this.deviceName = deviceName;
this.ip = ip;
this.imgid = imgid;
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item, null, true);
TextView titleText = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
Button startBtn = (Button) rowView.findViewById(R.id.startBtn);
Button stopBtn = (Button) rowView.findViewById(R.id.stopBtn);
final String URL3 = "http://damiangozdzi.nazwa.pl/pact-dev/sendstatus.php";
titleText.setText(deviceName[position]);
imageView.setImageResource(imgid[position]);
subtitleText.setText(ip[position]);
startBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Device has been started", Toast.LENGTH_SHORT).show();
SenderStatus s = new SenderStatus(getContext(), URL3, Integer.toString(position +1), "3");
s.execute();
//I tried to refresh my list from here but nothing worked
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Device has been stopped", Toast.LENGTH_SHORT).show();
SenderStatus s = new SenderStatus(getContext(), URL3, Integer.toString(position +1), "1");
s.execute();
}
});
return rowView;
}
}
User.java:
public class User extends Fragment {
private ListView list;
private Button startBtn;
private Button stopBtn;
private String[] deviceName ={};
private String[] ip ={};
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user, container, false);
Devices d = Devices.getInstance();
String s = d.getString();
String[][] all = getDevices(s);
deviceName = all[0];
ip = all[1];
String[] pre_imgid = all[2];
int x = pre_imgid.length;
Integer[] imgid = new Integer[x];
for (int i = 0; i < x; i++){
switch(pre_imgid[i]){
case "0":
imgid[i] = R.drawable.large_circle_szary; break;
case "1":
imgid[i] = R.drawable.large_circle_czerwony; break;
case "2":
imgid[i] = R.drawable.large_circle_pomarancz; break;
case "3":
imgid[i] = R.drawable.large_circle_zielony; break;
default:
imgid[i] = R.drawable.large_circle_niebieski; break;
}
}
ListAdapter adapter=new ListAdapter(getActivity(), deviceName, ip, imgid);
list = (ListView) view.findViewById(R.id.plcsList);
list.setAdapter(adapter);
return view;
}
public String[][] getDevices(String s){
char c = '{';
int count = 0;
for(int i=0; i < s.length(); i++)
{ if(s.charAt(i) == c)
count++;
}
String[][] all = new String[3][count];
if (s == null) {
Toast.makeText(getContext(), "s is null", Toast.LENGTH_SHORT).show();
} else {
try{
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
all[0][i] = obj.getString("address");
all[1][i] = obj.getString("name");
all[2][i] = Integer.toString(obj.getInt("status"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return all;
}
}
Welcome to Stackoverflow.
Create a method inside the adapter that receives your deviceName, ip, imgid as parameteres. Then you just need to call it when you click on the button.
On the adapter:
public void refreshData(String[] deviceName, String[] ip, Integer[] imgid){
this.deviceName = deviceName;
this.ip = ip;
this.imgid = imgid;
notifyDataSetChanged();
}
Then on the click button:
adapter.refreshData(yourDeviceNameVariable, yourIpVariable, yourImdidVariable);
I suggest you to put this code inside a method, where the deviceName, the ip and the imdid variable are global variables, and you call that method on button click, before refreshing the adapter.
Devices d = Devices.getInstance();
String s = d.getString();
String[][] all = getDevices(s);
deviceName = all[0];
ip = all[1];
String[] pre_imgid = all[2];
int x = pre_imgid.length;
Integer[] imgid = new Integer[x];
for (int i = 0; i < x; i++){
switch(pre_imgid[i]){
case "0":
imgid[i] = R.drawable.large_circle_szary; break;
case "1":
imgid[i] = R.drawable.large_circle_czerwony; break;
case "2":
imgid[i] = R.drawable.large_circle_pomarancz; break;
case "3":
imgid[i] = R.drawable.large_circle_zielony; break;
default:
imgid[i] = R.drawable.large_circle_niebieski; break;
}
}
This is something you need to workaround. I will be giving you the points to change but you need to update your code.
In onclicklistener of both start/stop you need to get the selected object manually and update there data, where by the view will be updated on the fly.
Here, you have to do something like, settag() to your parent layout with object from the list, i see there is multiple list, use the object of the list where you are updating the view.
Eg: // your parentlayout.setTag(devicename[position])
In onclicklistner, you need to get this object
Eg: // get your object from settag:- DeviceName dobj = (DeviceName) view.getTag()
Further:
dobj.updateview, // something your logic of updating view.
that's it, you are good to go but the problem is your class design.
Suggestion:
Create one more model class where your deviname and ip also the data/field you so want to edit/update in onclicklistener
Try to use list/map, preferably list to pass to adapter.

How to view data in database on fragment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to view data in database on fragment and I use TableRow to view data.
my code Setting database :
public class SqliteManager extends Activity {
public static final int VERSI_DATABASE= 1;
public static final String NAMA_DATABASE = "dbCrudSqlite";
public static final String NAMA_TABEL = "tbAgenda";
public static final String FIELD_ID = "_id";
public static final int POSISI_ID = 0;
public static final String FIELD_JUDUL = "judul";
public static final int POSISI_JUDUL = 1;
public static final String FIELD_DESKRIPSI = "deskripsi";
public static final int POSISI_DESKRIPSI = 2;
public static final String FIELD_WAKTU = "waktu";
public static final int POSISI_WAKTU = 3;
public static final String[] FIELD_TABEL ={ SqliteManager.FIELD_ID, SqliteManager.FIELD_JUDUL, SqliteManager.FIELD_DESKRIPSI, SqliteManager.FIELD_WAKTU };
private Context crudContext;
private SQLiteDatabase crudDatabase;
private SqliteManagerHelper crudHelper;
private static class SqliteManagerHelper extends SQLiteOpenHelper {
private static final String BUAT_TABEL =
"create table " + NAMA_TABEL + " (" +
SqliteManager.FIELD_ID + " integer primary key autoincrement, " +
SqliteManager.FIELD_JUDUL + " text not null, " +
SqliteManager.FIELD_DESKRIPSI + " text not null," +
SqliteManager.FIELD_WAKTU + " text not null " +
");";
public SqliteManagerHelper(Context context) {
super(context, NAMA_DATABASE, null, VERSI_DATABASE);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(BUAT_TABEL);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
public void generateData(SQLiteDatabase database){
ContentValues cv=new ContentValues();
cv.put(FIELD_ID, "3");
cv.put(FIELD_JUDUL, "Abang");
cv.put(FIELD_DESKRIPSI, "Abang");
cv.put(FIELD_WAKTU, "Merah");
database.insert(NAMA_TABEL,null,cv);
cv.put(FIELD_ID, "2");
cv.put(FIELD_JUDUL, "Opo");
cv.put(FIELD_DESKRIPSI, "Opo");
cv.put(FIELD_WAKTU, "Apa");
database.insert(NAMA_TABEL,null,cv);
}
public SqliteManager(Context context) {
crudContext = context;
}
public void bukaKoneksi() throws SQLException {
crudHelper = new SqliteManagerHelper(crudContext);
crudDatabase = crudHelper.getWritableDatabase();
generateData(crudDatabase);
}
public void tutupKoneksi() {
crudHelper.close();
crudHelper = null;
crudDatabase = null;
}
public long insertData(ContentValues values) {
return crudDatabase.insert(NAMA_TABEL, null, values);
}
public boolean updateData(long rowId, ContentValues values) {
return crudDatabase.update(NAMA_TABEL, values,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public boolean hapusData(long rowId) {
return crudDatabase.delete(NAMA_TABEL,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public Cursor bacaData() {
return crudDatabase.query(NAMA_TABEL,FIELD_TABEL,null, null, null, null,SqliteManager.FIELD_JUDUL + " DESC");
}
public Cursor bacaDataTerseleksi(long rowId) throws SQLException {
Cursor cursor = crudDatabase.query(true, NAMA_TABEL,FIELD_TABEL,FIELD_ID + "=" + rowId,null, null, null, null, null);
cursor.moveToFirst();
return cursor;
}
public ContentValues ambilData(String tempat, String lat, String lng) {
ContentValues values = new ContentValues();
values.put(SqliteManager.FIELD_JUDUL, tempat);
values.put(SqliteManager.FIELD_DESKRIPSI, lat);
values.put(SqliteManager.FIELD_WAKTU, lng);
return values;
}
public ArrayList<ArrayList<Object>> ambilSemuaBaris(){
ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try
{
cur = crudDatabase.query(NAMA_TABEL, new String[]{FIELD_ID,FIELD_JUDUL,FIELD_DESKRIPSI}, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast())
{
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(dataList);
}while (cur.moveToNext());
}
}catch (Exception e)
{
e.printStackTrace();
Log.e("DB ERROR",e.toString());
}
return dataArray;
}
}
I want to view data on fragment:
public class JawaIndo extends Fragment {
private SqliteManager sqliteDB;
private Activity activity;
TextView bhsjawa,bhsindo;
Button addBtn;
TableLayout tabel4data;
public JawaIndo(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
protected void updateTable() {
while (tabel4data.getChildCount()>1){
tabel4data.removeViewAt(1);
}
ArrayList<ArrayList<Object>> data = sqliteDB.ambilSemuaBaris();
for (int posisi = 0; posisi < data.size(); posisi++) {
TableRow tabelBaris = new TableRow(getActivity());
ArrayList<Object> baris = data.get(posisi);
TextView idTxt = new TextView(getActivity());
idTxt.setText(baris.get(0).toString());
tabelBaris.addView(idTxt);
TextView namaTxt = new TextView(getActivity());
namaTxt.setText(baris.get(1).toString());
tabelBaris.addView(namaTxt);
TextView hobiTxt = new TextView(getActivity());
hobiTxt.setText(baris.get(2).toString());
tabelBaris.addView(hobiTxt);
tabel4data.addView(tabelBaris);
}
}
}
Error when I write this code on class JawaIndo :
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
You have just change some in your onCreateView() method:
And it should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
//activity = new Activity();
// Update Here
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
In this passed your View's object named rootView as referenced to find the id of your UI element.
Didn't read all the code, just the snippet you highlighted and the logcat and even there spotted multiple problems:
The constraint failed comes when you're trying to call generateData() from onCreateView(). When running the code again, the very same data is re-inserted, causing the constraint failed failure.
Then, in here:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
You should never instantiate activities with new. Now all those findViewById()s will return null and get you a NullPointerException later on in updateTable().
You can not get reference of your from your activity instance. It will always get from the View only. The View class is responsible to initialize and find the views in your screen. So always find your views by layout only.
Here is your code:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
Change it as below. Change your reference of activity to rootView
activity = new Activity();
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();

Listview using Endless adapter

I have DB table with 10,000 rows which I want to display in the listview. I want to display first 20 and when the user scrolls down to the last item the next 20 should be loaded (and so on.). it really takes a lot of time to load all the datas in the listview so thats why i want it to load 20 datas first..
inside onCreate() Method the code is:
dbHelper = new WordDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
then on the displayListView() method the code is like this:
#SuppressWarnings("deprecation")
private void displayListView() {
final Cursor cursor = dbHelper.fetchAllWords();
// The desired columns to be bound
String[] columns = new String[] {
WordDbAdapter.KEY_WORD,
WordDbAdapter.KEY_ROWID,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.Word,
R.id.imgStar,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.word_info,
cursor,
columns,
to
);
ListView listView = (ListView) findViewById(R.id.Diclist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if(cursor != null){
if(lastInScreen == totalItemCount && isLoadingMore == false){
isLoadingMore = true;
loadedPage ++;
new LoadWords().execute();
}
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the word name from this row in the database.
String wordSelected =
cursor.getString(cursor.getColumnIndexOrThrow("word"));
String wordSyllabication =
cursor.getString(cursor.getColumnIndexOrThrow("syllabication"));
String wordPartofSpeech =
cursor.getString(cursor.getColumnIndexOrThrow("partofspeech"));
String wordMeaning =
cursor.getString(cursor.getColumnIndexOrThrow("meaning"));
String wordSpeak =
cursor.getString(cursor.getColumnIndexOrThrow("speakword"));
EditText TextDic = (EditText) findViewById(R.id.TextDic);
TextDic.setText(wordSelected);
speakMeaning = wordMeaning;
speakSyllabication = wordSyllabication;
speakPartOfSpeech = wordPartofSpeech;
speakWord = wordSpeak;
speakGetWord = wordSelected;
//Toast.makeText(getApplicationContext(),
// wordSyllabication + "\n" + wordPartofSpeech + "\n" + wordMeaning , Toast.LENGTH_SHORT).show();
}
});
EditText TextDic = (EditText) findViewById(R.id.TextDic);
TextDic.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
speakWord = "";
speakMeaning = "";
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchWordsByWord(constraint.toString());
}
});
}
then my AsyncTask is like this:
private class LoadWords extends AsyncTask<String, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(DictionaryActivity.this);
Cursor cursor = dbHelper.fetchAllWords();
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading books...");
this.dialog.show();
}
public void execute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(String... arg0) {
try{
cursor = dbHelper.fetchAllWords();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(final Void unused){
if(cursor != null){
if(dataAdapter == null){
startManagingCursor(cursor);
String[] columns = new String[] {
WordDbAdapter.KEY_WORD,
WordDbAdapter.KEY_ROWID,
};
int[] to = new int[] {
R.id.Word,
R.id.imgStar,
};
getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
dataAdapter = new SimpleCursorAdapter(DictionaryActivity.this, R.layout.word_info, cursor, columns, to);
ListView listView = (ListView) findViewById(R.id.Diclist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}else{
dataAdapter.notifyDataSetChanged();
}
}
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
isLoadingMore = false;
}
private AbsListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
The adapter doesn't load everything at once, and that should not be the reason you're seeing poor performance. ListView and SimpleCursorAdapter are fully capable of scrolling a list of only 10,000 items. The adapter only loads items as the user scrolls through the list. From the code that you've posted, I would say that your performance issues come from
dbHelper.deleteAllWords();
dbHelper.insertSomeWords();
If you post the code for these methods and dbHelper.fetchAllWords(), perhaps we can offer more help. Additionally, you can solve user interface problems by executing these long running tasks on a background thread (check out AsyncTask) and using a ProgressDialog to inform the user what is going on.
Take a look at Endless Adapter from the great Mark Murphy. It makes it really easy. You'll have your dataset that contains just the items you're displaying. In the adapter you can then tell it to grab the next set from your database and add it to the dataset.

Sorting a ListView with ArrayAdapter<String>

I have a custom ListView, each list item has four TextViews showing bank name, amount, date and time. This data is stored in a database. The idea is that on the Activity there is a quick action dialog which opens on clicking the sort button. The Dialog has three options as "Sort by bank name" ascending order, "Sort by Date" newest first and "Sort by amount" larger amount in the top of the list. I don't have any idea of how to proceed with the sorting task to be written in onItemClick(int pos). Can anyone please help me on this?
public class TransactionMenu extends Activity implements OnItemClickListener, OnActionItemClickListener {
String[] TransId ;
String[] mBankName;
String[] mAmount;
String[] mDate;
String[] mTime;
Button SortButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_screen);
SortButton = (Button)findViewById(R.id.sortKey);
//Bank Name action item
ActionItem bName = new ActionItem();
bName.setTitle("Bank Name");
bName.setIcon(getResources().getDrawable(R.drawable.bank_256));
//Amount action item
ActionItem amt = new ActionItem();
amt.setTitle("Amount");
amt.setIcon(getResources().getDrawable(R.drawable.cash));
//date action item
ActionItem date = new ActionItem();
date.setTitle("Date");
date.setIcon(getResources().getDrawable(R.drawable.calender));
//create quickaction
final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(bName);
quickAction.addActionItem(amt);
quickAction.addActionItem(date);
quickAction.setOnActionItemClickListener(this);
SortButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
//quickAction.setAnimStyle(QuickAction.ANIM_REFLECT);
}
});
DBAdapter lDBAdapter = new DBAdapter(this);
lDBAdapter.open();
/* getTransDetails() returns all the detials stored in the transaction table*/
Cursor mCursor =lDBAdapter.getAllTransDetails();
System.out.println("cur..........."+mCursor);
lDBAdapter.close();
if (mCursor != null) {
int size = mCursor.getCount();
if (mCursor.moveToFirst()) {
TransId = new String[size];
mAmount = new String[size];
mBankName = new String[size];
mDate = new String[size];
mTime = new String[size];
for (int i = 0; i < size; i++, mCursor.moveToNext()) {
TransId[i] = mCursor.getString(0);
mAmount[i] = mCursor.getString(1);
mBankName[i] = mCursor.getString(3);
mDate[i] = mCursor.getString(2);
mTime[i] = mCursor.getString(4);
}
}
}
for (int i = 0; i < mCursor.getCount(); i++) {
System.out.println("TransId is+++++++++++++++ "+TransId[i]);
System.out.println("amount is+++++++++++++++ "+mAmount[i]);
System.out.println("bankName is+++++++++++++++ "+mBankName[i]);
System.out.println("date is+++++++++++++++ "+mDate[i]);
System.out.println("time is+++++++++++++++ "+mTime[i]);
}
ListView myListView = (ListView) findViewById(R.id.transactionListView);
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
myListView.setAdapter(myAdapterObj);
myListView.setOnItemClickListener((OnItemClickListener) this);
}
private class MyBaseAdapter extends ArrayAdapter<String> {
public MyBaseAdapter(Context context, int textViewResourceId, String[] transId) {
super(context, textViewResourceId, transId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView label = (TextView)row.findViewById(R.id.textview1);
label.setText("Amount: "+mAmount[position]);
TextView label1 = (TextView) row.findViewById(R.id.textview2);
label1.setText("Bank Name: "+mBankName[position]);
TextView label2 = (TextView) row.findViewById(R.id.textview3);
label2.setText("Date: "+mDate[position]);
TextView label3 = (TextView) row.findViewById(R.id.textview4);
label3.setText("Time: "+mTime[position]);
return row;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("arg2 is++++++++++++++"+arg2);
int lRowId = Integer.parseInt(TransId[arg2]);
}
public void onItemClick(int pos) {
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
if (pos == 0) {
Toast.makeText(TransactionMenu.this, "Bank name item selected", Toast.LENGTH_SHORT).show();
}
else if (pos ==1) {
Toast.makeText(TransactionMenu.this, "amount item selected", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TransactionMenu.this, "Date item selected", Toast.LENGTH_SHORT).show();
}
}
}
I will give you the way i would do this, not the best probably but it will work fine.
Fisrt of all as user7777777777 said it's better to keep related infos into the same object so i'd define BankInfo class as shown below:
private class BankInfo{
String TransId ;
String mBankName;
String mAmount;
String mDate;
String mTime;
public BankInfo(String TransId,String mBankName,String mAmount,String mDate,String mTime)
{
//fields init
}
}
once you have this you will define an Array of this object BankInfo[] trans. In the adapter you can use this array to bind values into views.
then to manage to implement the sorting function the thing i would do is to put a static variable into the BankInfo class and override the CompareTo() method to use that field:
static int AMMOUNT = 0;
static int DATE = 1;
static int NAME = 2;
static public int sort_by;
public int compareTo(BankInfo info){
switch (sorty_by){
case(AMMOUNT):
return //compare by ammount
case(DATE):
return //compare by date
case(NAME):
return //compare by name
}
}
with this inside of BankInfo you will have only to add your array to a TreeSet<BankInfo> and all your item will be sortet using the compareTo() method.
Inside the adapter put this method to sort elements in the adapter
public void sort_datas(int sort_by);
{
//set the type of sort you want
BankInfo.sortBy = sort_by;
//build a Sorted treeSet by the BankInfo array
TreeSet<BankInfo> sorted_info = new TreeSet<BankInfo>();
list.addAll(Arrays.asList(trans));
//replace the BankInfo array with the new sorted one
trans = (BankInfo[])sorted_info.toArray();
//notify to the adapter that the data set changed
notifyDataSetChanged();
}
You can use the following code. You need to maintain the bank info in a BankInfo object. Create an ArrayList of BankInfo objects and then you can use this code. Its not a good practice to keep related info into separate arrays.
Collections.sort(mBankInfoArrayList, new Comparator<BankInfo>() {
int compare(BankInfo obj1, BankInfo obj2) {
return obj1.getBankName().compareToIgnoreCase(obj2.getBankName());
}
});

Categories