I am a very new android developer and I have been trying to learn it by creating simple apps.
Right now I'm stuck on trying to create a custom ListView for my app.
My data's are being stored in SQLite and I'm calling these data's as a List. I can't seem to find a website to demonstrate how to get SQLite data's to work with Custom ListView.
Below are my data's and I hope someone can help me with setting up my custom adapter to work with my sqlite data's.
Records.java
public class Records {
private long id;
private String name;
private String type;
private float mf;
private float mftop;
private float mfbot;
private float mfleft;
private float mfright;
private float rf;
private float rftop;
private float rfbot;
private float rfleft;
private float rfright;
private float tb;
private float tbtop;
private float tbbot;
private float tbleft;
private float tbright;
private float bridge;
private float bridgel;
private float bridger;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
// Middle Finger
public float getMF() {
return mf;
}
public void setMF(float mf) {
this.mf = mf;
}
public float getMFTop() {
return mftop;
}
public void setMFTop(float mftop) {
this.mftop = mftop;
}
public float getMFBot() {
return mfbot;
}
public void setMFBot(float mfbot) {
this.mfbot = mfbot;
}
public float getMFLeft() {
return mfleft;
}
public void setMFLeft(float mfleft) {
this.mfleft = mfleft;
}
public float getMFRight() {
return mfright;
}
public void setMFRight(float mfright) {
this.mfright = mfright;
}
//Ring Finger
public float getRF() {
return rf;
}
public void setRF(float rf) {
this.rf = rf;
}
public float getRFTop() {
return rftop;
}
public void setRFTop(float rftop) {
this.rftop = rftop;
}
public float getRFBot() {
return rfbot;
}
public void setRFBot(float rfbot) {
this.rfbot = rfbot;
}
public float getRFLeft() {
return rfleft;
}
public void setRFLeft(float rfleft) {
this.rfleft = rfleft;
}
public float getRFRight() {
return rfright;
}
public void setRFRight(float rfright) {
this.rfright = rfright;
}
//Thumb
public float getTB() {
return tb;
}
public void setTB(float tb) {
this.tb = tb;
}
public float getTBTop() {
return tbtop;
}
public void setTBTop(float tbtop) {
this.tbtop = tbtop;
}
public float getTBBot() {
return tbbot;
}
public void setTBBot(float tbbot) {
this.tbbot = tbbot;
}
public float getTBLeft() {
return tbleft;
}
public void setTBLeft(float tbleft) {
this.tbleft = tbleft;
}
public float getTBRight() {
return tbright;
}
public void setTBRight(float tbright) {
this.tbright = tbright;
}
//Bridge
public float getBridge() {
return bridge;
}
public void setBridge(float bridge) {
this.bridge = bridge;
}
public float getBridgeL() {
return bridgel;
}
public void setBridgeL(float bridgel) {
this.bridgel = bridgel;
}
public float getBridgeR() {
return bridger;
}
public void setBridgeR(float bridger) {
this.bridger = bridger;
}
//Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return name;
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<NTAdapter> {
Context context;
int layoutResourceId;
NTAdapter data[] = null;
public CustomAdapter(Context context, int layoutResourceId, NTAdapter[] data) {
super(context, layoutResourceId, data);
// TODO Auto-generated constructor stub
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
DataHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder();
holder.dataName = (TextView)row.findViewById(R.id.dataName);
holder.dataType = (TextView)row.findViewById(R.id.dataType);
row.setTag(holder);
} else {
holder = (DataHolder)row.getTag();
}
NTAdapter ntadapter = data[position];
holder.dataName.setText(ntadapter.name);
holder.dataType.setText(ntadapter.type);
return row;
}
static class DataHolder {
TextView dataName;
TextView dataType;
}
}
NTAdapter.java
public class NTAdapter {
public int id;
public String name, type;
public NTAdapter() {
super();
}
public NTAdapter(int id, String name, String type) {
super();
this.id = id;
this.name = name;
this.type = type;
}
}
DataLayout.java
public class DataLayout extends ListActivity {
private RecordsDataSource datasource;
Button btnDataCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_layout);
datasource = new RecordsDataSource(this);
datasource.open();
List<Records> values = datasource.getAllRecords();
//use the SimpleCursorAdapter to show the
//elements in a ListView
ArrayAdapter<Records> adapter = new ArrayAdapter<Records>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
/**
CustomAdapter adapter = new CustomAdapter(this, R.layout.data_layout_listview, values);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
*/
Button btnDataCancel = (Button)findViewById(R.id.btnDataCancel);
//Cancel Button
btnDataCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent goMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(goMain);
finish();
}
});
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Please note that within my DataLayout.java, I have been trying to get my sqlite data's to work with my custom listview setup.
/**
CustomAdapter adapter = new CustomAdapter(this, R.layout.data_layout_listview, values);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
*/
I do know that my problem is that my NTAdapter.java and my CustomAdapter.java aren't being setup properly. However, I don't know how to fix it so that it will accept the list of data's which are being stored in values
As the code started to get abit too long to read, I didn't post my other classes. But please do note that everything is working fine if I'm not using my custom listview, as it is not yet working.
Any help will be appreciated. Thank you in advance.
edit: Also, I know that NTAdapter isn't really needed, but I don't know how to make it so that my CustomAdapter.java will get the data's from my values and uses them to setup my custom ListView.
edit2: For those that are wondering what values is, please refer to DataLayout.java.
.
What you are doing while making a CustomAdapter is that you are trying to pass a List
to a constructor which accepts NTAdapter array . So your program is not supposed to work properly.
What you could do is make your CustomAdapter class something like the following :
public class CustomAdapter extends ArrayAdapter<Records> {
Context context;
int layoutResourceId;
List<Records> data;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<Records> data) {
super(context, layoutResourceId, data);
// TODO Auto-generated constructor stub
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data=data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
DataHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder();
holder.dataName = (TextView)row.findViewById(R.id.dataName);
holder.dataType = (TextView)row.findViewById(R.id.dataType);
row.setTag(holder);
} else {
holder = (DataHolder)row.getTag();
}
Records records = data.get(position);
holder.dataName.setText(records.getName());
holder.dataType.setText(records.getType());
return row;
}
static class DataHolder {
TextView dataName;
TextView dataType;
}
Related
This question already has answers here:
Using context in a fragment
(31 answers)
Closed 3 years ago.
i try to make custom listview, then I get errors, and i don't know why.
there was an error at this, R.layout.list_events_item,listEvents
and the error message is:
EventsFragment.java
public class EventsFragment extends Fragment {
private View paramView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.fragment_events,container,false);
ListView listView = (ListView) paramView.findViewById(R.id.listViewEvents);
List<Events> listEvents = new ArrayList<Events>();
Events events = new Events(1,"12:00","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
events = new Events(2,"11:20","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
listView.setAdapter(new EventsAdapter(this, R.layout.list_events_item,listEvents));
return paramView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
}
EventsAdapter.java
public class EventsAdapter extends ArrayAdapter<Events> {
List<Events> listEvents;
Context context;
int layout;
public EventsAdapter(Context context, int layout, List<Events> listEvents){
super(context,layout,listEvents);
this.context=context;
this.layout=layout;
this.listEvents=listEvents;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
EventsHolder holder;
if (v == null){
LayoutInflater vi=((Activity)context).getLayoutInflater();
holder = new EventsHolder();
holder.time=(TextView) v.findViewById(R.id.time);
holder.signature = (TextView) v.findViewById(R.id.signatureId);
holder.sensor = (TextView) v.findViewById(R.id.sensor);
holder.attacker = (TextView) v.findViewById(R.id.attacker);
holder.attacked = (TextView) v.findViewById(R.id.attacked);
v.setTag(holder);
}else {
holder=(EventsHolder) v.getTag();
}
Events events = listEvents.get(position);
holder.time.setText(events.getTime());
holder.signature.setText(events.getSignature_id());
holder.sensor.setText(events.getSensor());
holder.attacker.setText(events.getAttacker_port());
holder.attacked.setText(events.getAttacked_port());
return v;
}
static class EventsHolder{
TextView time;
TextView signature;
TextView sensor;
TextView attacker;
TextView attacked;
}
}
my Events model
public class Events {
int id;
String time;
String signature_id;
String alert_message;
String ip_source;
String ip_destination;
String sensor;
String protocol;
int attacker_port;
int attacked_port;
public Events(int id, String time, String signature_id, String alert_message, String ip_source, String ip_destination, String sensor, String protocol, int attacker_port, int attacked_port) {
this.id = id;
this.time = time;
this.signature_id = signature_id;
this.alert_message = alert_message;
this.ip_source = ip_source;
this.ip_destination = ip_destination;
this.sensor = sensor;
this.protocol = protocol;
this.attacker_port = attacker_port;
this.attacked_port = attacked_port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSignature_id() {
return signature_id;
}
public void setSignature_id(String signature_id) {
this.signature_id = signature_id;
}
public String getAlert_message() {
return alert_message;
}
public void setAlert_message(String alert_message) {
this.alert_message = alert_message;
}
public String getIp_source() {
return ip_source;
}
public void setIp_source(String ip_source) {
this.ip_source = ip_source;
}
public String getIp_destination() {
return ip_destination;
}
public void setIp_destination(String ip_destination) {
this.ip_destination = ip_destination;
}
public String getSensor() {
return sensor;
}
public void setSensor(String sensor) {
this.sensor = sensor;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getAttacker_port() {
return attacker_port;
}
public void setAttacker_port(int attacker_port) {
this.attacker_port = attacker_port;
}
public int getAttacked_port() {
return attacked_port;
}
public void setAttacked_port(int attacked_port) {
this.attacked_port = attacked_port;
}
}
Try changing this to getActivity()
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
I have created a ListActivity and read data from SQLite to show in ListView.
then , I need to click on list and show my data in new layout but I have a problem when I use
onClickListener so this is my code below
MainActivity.java
import com.hci.Entry.NoteEntry;
import com.hci.data.Constants;
import com.hci.data.ReminderDB;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
private ReminderDB dba;
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new ReminderDB(this);
dba.open();
setContentView(R.layout.reminder_main);
super.onCreate(savedInstanceState);
this.setListAdapter(new NoteAdapter(this));
}
}
private class NoteAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private ArrayList<NoteEntry> notes;
public NoteAdapter(Context context){
mInflater = LayoutInflater.from(context);
notes = new ArrayList<NoteEntry>();
getData();
}
public void getData(){
Cursor c = dba.getNote();
startManagingCursor(c);
if(c.moveToFirst()){
do {
String title = c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String subject = c.getString(c.getColumnIndex(Constants.SUBJECT_NAME));
String content = c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
NoteEntry temp = new NoteEntry(title,content,subject);
notes.add(temp);
}while(c.moveToNext());
}
}
private Holder holder;
#Override
public int getCount() {
return notes.size();
}
#Override
public NoteEntry getItem(int i) {
return notes.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
if(view == null){
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.note_row,null);
holder = new Holder();
holder.subject = (TextView) view.findViewById(R.id.subject_name);
holder.title = (TextView) view.findViewById(R.id.Note_content);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
holder.mNote = getItem(position);
holder.title.setText(holder.mNote.getTitle());
holder.subject.setText(holder.mNote.getSubject());
view.setTag(holder);
return view;
}
private class Holder {
NoteEntry mNote;
public TextView subject;
public TextView title;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_button:
newActivities();
return true;
case R.id.action_settings:
openSetting();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void newActivities() {
Intent newActivities = new Intent(getApplicationContext(),NewActivities.class);
startActivity(newActivities);
}
private void openSetting() {
// TODO Auto-generated method stub
}
#Override
public void onBackPressed(){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//now I have a problem
Cursor selectNote = (Cursor) l.getItemAtPosition(position);
String title = selectNote.getString(selectNote.getColumnIndex(Constants.TITLE_NAME));
String subject = selectNote.getString(selectNote.getColumnIndex(Constants.SUBJECT_NAME));
String content = selectNote.getString(selectNote.getColumnIndex(Constants.CONTENT_NAME));
Log.d("Title = ",title);
Log.d("Subject = ",subject);
Log.d("Content = ",content);
}
}
NoteDBHelper.java
public class NoteDBHelper extends SQLiteOpenHelper {
private static final String CREATE_TABLE = "create table "+Constants.TABLE_NAME+"("+
Constants.NOTE_ID+" integer primary key autoincrement, "+
Constants.TITLE_NAME+" text not null, "+
Constants.SUBJECT_NAME+" text not null, "+
Constants.CONTENT_NAME+" text not null);";
public NoteDBHelper(Context context) {
super(context, Constants.TABLE_NAME, null, Constants.DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter","Upgrading from version"+oldVersion+"to"+newVersion+",which will destroy all old data");
db.execSQL("drop table if exists"+Constants.TABLE_NAME);
onCreate(db);
}
}
ReminderDB.java
public class ReminderDB {
private SQLiteDatabase db;
private final Context context;
private final NoteDBHelper dbhelper;
private String[] allcolumns = {Constants.SUBJECT_NAME,Constants.TITLE_NAME,Constants.CONTENT_NAME};
public ReminderDB(Context c){
context = c;
dbhelper = new NoteDBHelper(context);
db = dbhelper.getWritableDatabase();
}
public void close(){
db.close();
}
public void open() throws SQLiteException {
db = dbhelper.getWritableDatabase();
}
public long insertNotes(String title,String content,String S_name){
ContentValues newTaskValue = new ContentValues();
newTaskValue.put(Constants.TITLE_NAME, title);
newTaskValue.put(Constants.CONTENT_NAME, content);
newTaskValue.put(Constants.SUBJECT_NAME, S_name);
return db.insert(Constants.TABLE_NAME, null,newTaskValue );
}
public Cursor getNote(){
Cursor cursor = db.query(Constants.TABLE_NAME,allcolumns,null,null,null,null,null);
return cursor;
}
}
NoteEntry.java
public class NoteEntry {
int id;
String title, subject, content;
public NoteEntry(String t,String c,String s){
title = t;subject = s;content = c;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
thanks for help :))
I guess you are getting ClassCastException error. Your adapter is populated with NoteEntry object instances while you are trying to convert it to Cursor instance. So, instead of
(Cursor)l.getItemAtPosition(position);
use the following:
(NoteEntry)l.getItemAtPosition(position);
I have an activity that contains a List. This list will take the data from SQLite:
public class RecentCases extends Activity {
Button GoToCaseInfo, CreateNewFormB;
RecentCaseClass recent1;
// the adapter class..
class RecentCasesInfoAdapter extends ArrayAdapter<RecentCaseClass>
{
public RecentCasesInfoAdapter() {
super(RecentCases.this, R.layout.recent_cases_row);
}
public View getView(final int position, View convertView,
ViewGroup parent)
{
recent1 = this.getItem(position);
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.recent_cases_row, parent,
false);
// this is our row items..
TextView recentName = (TextView) row
.findViewById(R.id.tvrecentName);
TextView recenInfo = (TextView) row.findViewById(R.id.recent_info);
ImageView recentImg = (ImageView) row.findViewById(R.id.list_image);
// TODO What's the info they want
// String CaseTime = recent1.getTime();
// recentName.setText(recent1.getName());
// recenInfo.setText("His/her age: " + recent1.getAge() +
// " year old"
// + " Lost sicnce :" + CaseTime);
String CasePicPath;
// TODO Linear or ??
RelativeLayout rowLayout = (RelativeLayout) row.findViewById(R.id.row_layout);
rowLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// go to
Intent k = new Intent(RecentCases.this, Case_Information.class);
startActivity(k);
}
});
return row;
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_cases);
// Moving to Create New Form Activity
CreateNewFormB = (Button) findViewById(R.id.cretnwfrmRC);
CreateNewFormB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent k = new Intent(RecentCases.this, CreateNewForm.class);
startActivity(k);
}
});
// For list
// Intilaize
ListView RecentCasesListView = (ListView) findViewById(R.id.recent_cases_list);
// create adapter
RecentCasesInfoAdapter recentCasesInfoAdapter = new RecentCasesInfoAdapter();
// 1-First receives MMS OnReceive Class 2- Assign the MMS info to Static
// Array 3- Assign the array to the adapater
// for(MedicineClass m: Model.getMedList()) MedicineInfoAdapter.add(new
// MedicineClass(m));
recentCasesInfoAdapter.add(recent1);
// after fill the adapter.. assign the list to the adapter
RecentCasesListView.setAdapter(recentCasesInfoAdapter);
}
}
and this is the class
public class RecentCaseClass {
private String pic;
private String name;
private String gender;
private int age;
private String clothes;
private String MoreInfo;
private String time;
private String location;
private int ID;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClothes() {
return clothes;
}
public void setClothes(String clothes) {
this.clothes = clothes;
}
public String getMoreInfo() {
return MoreInfo;
}
public void setMoreInfo(String moreInfo) {
MoreInfo = moreInfo;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
}
The SMS will come to my app then i will save in SQLite then i should show it in my app
How can i take data from SQLite and show it in list?
If I delete the row information from SQLite how can i delete the row in list?
Should i change the adapter?
============================UPDATE===========================
I add this to my project but I did not change any thing just added this class:
public class RecentClassAdapter extends BaseAdapter{
private RecentCases RecentCases;
static public List<RecentCaseClass> listOfRCases;
RecentCaseClass entry;
int caseId;
public RecentClassAdapter(RecentCases recentcases, List<RecentCaseClass> listOfCaseParameter) {
this.RecentCases = recentcases;
this.listOfRCases = listOfCaseParameter;
}
public int getCount() {
return listOfRCases.size();
}
public Object getItem(int position) {
return listOfRCases.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
entry = listOfRCases.get(position);
caseId = entry.getID();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) RecentCases.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.recent_cases_row, null);
}
// this is row items..
// Set the onClick Listener on this button
//ConfExpandRegion = (Button) convertView.findViewById(R.id.expand);
//Button Cancelb = (Button) convertView.findViewById(R.id.cancelCase);
TextView RCase = (TextView) convertView.findViewById(R.id.tvrecentName);
RCase.setText(entry.getName());
Toast.makeText(RecentCases, "inside getview" + entry.getAge(), 0).show();
public void add(RecentCaseClass RCaseClass) {
// TODO Auto-generated method stub
listOfRCases.add(RCaseClass);
}
}
}
You have to create a custom array adapter and fetch the data from Database row by row and populate in your Listview with getView method.
Here is a example for custom array adapter
http://android-er.blogspot.in/2010/06/custom-arrayadapter-with-with-different.html
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
Hello everyone i have a problem in my application. The check in my check box, once i check the check box and scroll it down/up the check is gone, i didn't know how that happen. can anyone help me with this? THANKS for the help :)
HERE IS MY CODE:
public class TaskKiller extends Activity {
private static final String TAG = "TaskKillerActivity";
TaskListAdapter adapter;
ListView lv;
private List<TaskObject> getTasksToKill() {
List<TaskObject> tol = new ArrayList<TaskObject>();
for (int i = 0; i < adapter.getCount(); i++) {
TaskObject to = adapter.getItem(i);
if (to.isToKill()) {
tol.add(to);
}
}
return tol;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public void loadRunningProcesses() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appinfolist = activityManager
.getRunningAppProcesses();
Log.d(TAG, "AppInfoList Size: " + appinfolist.size());
for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : appinfolist) {
TaskObject runningtask = new TaskObject();
runningtask.setPid(runningAppProcessInfo.pid);
runningtask.setProcessName(runningAppProcessInfo.processName);
adapter.addTask(runningtask);
}
}
class TaskObject {
int pid;
String processName;
private boolean toKill;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public boolean isToKill() {
return toKill;
}
public void setToKill(boolean toKill) {
this.toKill = toKill;
}
}
class TaskListAdapter extends BaseAdapter {
private static final String TAG = "TaskListAdapter";
ArrayList<TaskObject> list;
Context context;
public TaskListAdapter(Context context) {
Log.d(TAG, "created new task list adapter");
this.context = context;
if (list == null) {
list = new ArrayList<TaskKiller.TaskObject>();
}
}
public void addTask(TaskObject taskObject) {
list.add(taskObject);
}
public void clearTasks() {
list.clear();
Log.d(TAG, "list size:" + list.size());
this.notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public TaskObject getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
RelativeLayout rl = new RelativeLayout(context);
TextView textPid = new TextView(context);
textPid.setId(222222);
textPid.setText(Integer.toString(getItem(position).getPid()));
TextView textName = new TextView(context);
textName.setId(333333);
textName.setText(getItem(position).getProcessName());
CheckBox chckKill = new CheckBox(context);
chckKill.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// is chkIos checked?
if (((CheckBox) v).isChecked()) {
getItem(position).setToKill(true);
}
}
});
}
I think the issue is that you aren't using the item's toKill status into the Checkbox. When you scroll, it get's redrawn with getView - and is reset to empty.
add
chckKill.setChecked( ((TaskObject) getItem(position) ).isToKill());
after the constructor.