Related
I have two activities that are called DrinksActivity and FoodsActivity. Both have their own RecyclerViews to display items.
They work well, but I have to pass their values to another activity called.. sample_activity.
This is how sample_activity looks like.
public class sample_layout extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_layout);
SetTexts();
Navigation();
TextView textView = findViewById(R.id.txtFoodName);
Intent intent = getIntent();
DrinksModel drinksM = intent.getParcelableExtra("drinks");
FoodModel foodM = intent.getParcelableExtra("foods");
//how can i set the textView from their own getParcelableExtra values
String FoodName = foodM.getFoodName();
textView.setText(FoodName);
//how can i set the textView from their own getParcelableExtra values
String DrinkName = drinksM.getDrinkName();
textView.setText(DrinkName);
}
public String getName(String email) {
String stringList = null;
DatabaseHelperAccounts db = new DatabaseHelperAccounts(this);
SQLiteDatabase dbb = db.getWritableDatabase();
String selectQuery = "SELECT FullName FROM " + db.DATABASE_TABLE + " WHERE email = '" + email + "'";
Cursor c = dbb.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
String name2 = (c.getString(c.getColumnIndex("FullName")));
stringList = name2;
c.moveToNext();
}
}
return stringList;
}
public void SetTexts() {
String StringEmail = LoginFragment.EmailString;
NavigationView nav_view = (NavigationView) findViewById(R.id.nv);//this is navigation view from my main xml where i call another xml file
View header = nav_view.getHeaderView(0);//set View header to nav_view first element (i guess)
TextView UserFullNameNav = (TextView) header.findViewById(R.id.UserFullNameNav);//now assign textview imeNaloga to header.id since we made View header.
TextView UserEmailNav = (TextView) header.findViewById(R.id.UserEmailNav);
getName(StringEmail);
UserEmailNav.setText(StringEmail);// And now just set text to that textview
UserFullNameNav.setText(getName(StringEmail));
}
public void Navigation() {
dl = findViewById(R.id.sampleLayout);
t = new ActionBarDrawerToggle(this, dl, R.string.open, R.string.close);
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.itemDrinks:
Intent DrinksIntent = new Intent(getApplicationContext(), DrinksActivity.class);
startActivity(DrinksIntent);
break;
case R.id.itemFoods:
Intent FoodsIntent = new Intent(getApplicationContext(), FoodsActivity.class);
startActivity(FoodsIntent);
break;
case R.id.itmLogout:
Intent LogOut = new Intent(getApplicationContext(), MainActivity.class);
startActivity(LogOut);
finish();
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull 'MenuItem' item)
{
if ( t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
How can I get the value of the item when it is chosen from the recyclerview of that specific activity?
Try to use this
if (getIntent()!=null ){
if (getIntent.hasExtra("drinks")){
DrinksModel drinksM = intent.getParcelableExtra("drinks");
String DrinkName = drinksM.getDrinkName();
textView.setText(DrinkName);
}else if(getIntent.hasExtra("foods")){
FoodModel foodM = intent.getParcelableExtra("foods");
String FoodName = foodM.getFoodName();
textView.setText(FoodName);
}
}
As I can see you're using database to store data, right? If so, the best (and the most correct) way is to pass some identifier between activity (like "id") and then get value by that id from database where you need. But, if you really want to pass the whole object then you need to use serializable or parcelable (parcelable is better choice since it's from Android SDK). Then in the activity where you're getting the value just parse it.
EDIT:
To get parcelable value call:
Food food = getIntent().getExtras().getParcelable("food");
Then just call:
textView.setText(food.getYourField);
This question already has an answer here:
Reading all contact data
(1 answer)
Closed 5 years ago.
I try to make Contact App and now I try to read the Contacts
I have 450 contacts and its take something like 60 sec to read them all.
I do it with Contact class:
public class Contact {
String name;
public ArrayList<String> PhoneNumber = new ArrayList<>();
public ArrayList<String> Email = new ArrayList<>();
int NumberOfPhones = 0;
int NumberOfMails = 0 ;
}
and I read like this :
tatic final int CODE_FOR_PERMISSION = 123;
List<Contact> ListContact = new ArrayList<Contact>();
Contact TempContact;
String TempName ="";
ArrayList<String> TempPhoneNumber = new ArrayList<>();
public ArrayList<String> TempEmail = new ArrayList<>();
int TempCounter = 0;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_activity);
AskForPermission();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
//init();
//OnAction();
void init(){
textView = (TextView) findViewById(R.id.chekk);
}
void OnAction(){
TempContact.PrintToTextView(textView,ListContact);
}
public void getContacts() {
contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
TempName = name;
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
TempPhoneNumber.add(phoneNumber);
}
phoneCursor.close();
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
TempEmail.add(email);
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}
// Add the contact to the ArrayList
contactList.add(output.toString());
TempContact = new Contact(TempName,TempPhoneNumber,TempEmail);
ListContact.add(TempContact);
TempName = "";
TempPhoneNumber.clear();
TempEmail.clear();
}
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 5);
}
}
how I can make the reading from contacts faster?
I have searched in other sutes but I don't know how to do it faster.
it can be done because the default contact app in the phone makes it very fast.
You don't need to query for all contacts + all emails + all phones to display the main contacts list similar to the default contacts app.
You'd probably notice that the main screen of all contacts apps display only names + picture, and not emails or phones.
Just perform the first query in your code to display the list of contacts, and only when the user clicks on one of those contacts, you'll open a new activity with the details of that specific contact only (which is a short query to make)
My app contains a series of long texts, and I'd like the user to be able to return to them at the point where they left off if they leave that View.
I've adapted the code from this answer for a ListView. The first Log is fine, but the second does not, which suggests to me that state is null.
Here's my StoryBodyActivity:
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
Parcelable state;
#Override
public void onPause() {
Log.d("pause", "saving listview state # onPause");
state = storyBodyTextView.onSaveInstanceState();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(story);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
}
}
I also need to ensure that the position of each individual long text is saved.
Here's the DatabaseHelper to show where the data is coming from:
public String getStoryBody(String story) {
Log.i("test", "hello");
String storyBody = "";
// Select all query
String selectQuery = "SELECT * FROM " + BOOKS + " WHERE title = '" + story + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
storyBody = cursor.getString(4);
} while (cursor.moveToNext());
}
return storyBody;
}
In my project there is a list of category and every category has multiple item .I want to store these category with its multiple items.My question is can i store it in sqlite and i want retrieve it in recycle view.
[![In the screenshot every category is given with the selection number.i want to insert it with category with its multiple items and also want to show as given in screenshots][1]][1]
[1]: https://i.stack.imgur.com/9WaKm.png `public class ViewAllAdapter extends RecyclerView.Adapter {
private ArrayList<StringMenuListBean> dataList;
private Context mContext;
private TextView itemText;
private List<String> itemList;
public ViewAllAdapter(Context context, ArrayList<StringMenuListBean> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem_viewall, null);
v.setLayoutParams(new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT
));
ItemRowHolder mh = new ItemRowHolder(v, mContext);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int position) {
itemList = new ArrayList<>();
final StringMenuListBean model = dataList.get(position);
String str = model.getName();
String category = str.substring(0, str.indexOf("-"));
String item = str.substring(str.indexOf("-") + 1, str.length());
itemList.add(item);
itemRowHolder.linear.removeAllViews();
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
Log.e("category", category);
Log.e("remainder", item);
itemRowHolder.tv_category_item.setText(category + " :");
for (int k = 0; k < itemList.size(); k++) {
itemText = new TextView(mContext);
itemText.setText((position + 1) + " ." + item);
itemText.setTextColor(Color.parseColor("#43A047"));
itemText.setLayoutParams(llp);
itemRowHolder.linear.addView(itemText);
}
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tv_category_item;
protected LinearLayout linear;
public ItemRowHolder(View view, final Context mContextv) {
super(view);
tv_category_item = (TextView) view.findViewById(R.id.tv_category_item);
linear = (LinearLayout) view.findViewById(R.id.linear);
}
}
}
here is my Activitypublic class ViewAllActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView viewall_recycleview;
ViewAllAdapter viewallAdapter;
TextView tv_ID;
TextView tv_PACKID;
TextView tv_PACKAGENAME;
TextView tv_USERID;
TextView tv_USER_NAME;
TextView tv_CATID;
TextView tv_CATNAME;
TextView tv_MENUITEMS;
TextView tv_MEMBER;
TextView tv_DATE;
TextView tv_TIME;
TextView tv_TOTAL_PRICE;
TextView tv_ORDER_TYPE;
TextView tv_DISCOUNT;
TextView tv_CITY;
TextView tv_PROMOCODE;
TextView tv_PAYMENT_STATUS;
TextView tv_PRICE;
TextView tv_MENUID;
TextView tv_SUBPACKAGENAME;
TextView tv_CURRENT_DATE;
Button btn_download;
MenuDetailBean menuDetailBean;
Bundle activitybundle;
String subpackage_id, pack_id;
String menuitem;
ArrayList<StringMenuListBean> stringMenuList;
StringMenuListBean stringMenu;
List<String> menulist;
List<String> arraylist1;
File imagePath;
RecyclerView rcyView_mymenu;
Bitmap bitmap;
View view;
ByteArrayOutputStream bytearrayoutputstream;
File file;
FileOutputStream fileoutputstream;
boolean boolean_save;
LinearLayout ll_linear;
MenuAdapter menuAdapter;
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewall);
init();
setTextAndList();
btn_download.setOnClickListener(this);
}
private void init() {
activitybundle = getIntent().getExtras();
pack_id = activitybundle.getString("pack_id");
subpackage_id = activitybundle.getString("sub_package_id");
// Log.e("subpackage_id",subpackage_id);
bytearrayoutputstream = new ByteArrayOutputStream();
rcyView_mymenu = (RecyclerView) findViewById(R.id.rcyView_mymenu);
rcyView_mymenu.setNestedScrollingEnabled(false);
tv_SUBPACKAGENAME = (TextView) findViewById(R.id.tv_SUBPACKAGENAME);
tv_PRICE = (TextView) findViewById(R.id.tv_PRICE);
tv_TOTAL_PRICE = (TextView) findViewById(R.id.tv_TOTAL_PRICE);
tv_DATE = (TextView) findViewById(R.id.tv_DATE);
tv_TIME = (TextView) findViewById(R.id.tv_TIME);
tv_MEMBER = (TextView) findViewById(R.id.tv_MEMBER);
tv_ORDER_TYPE = (TextView) findViewById(R.id.tv_ORDER_TYPE);
btn_download = (Button) findViewById(R.id.btn_download);
ll_linear = (LinearLayout) findViewById(R.id.ll_linear);
}
private void setTextAndList() {
menuDetailBean = DbUtils.getMenuDetail(getApplicationContext(), pack_id);
tv_SUBPACKAGENAME.setText(menuDetailBean.getSUBPACKAGE_NAME());
tv_PRICE.setText(menuDetailBean.getPRICE() + "/-");
tv_TOTAL_PRICE.setText(menuDetailBean.getTOTAL_PRICE() + "Rs.");
tv_DATE.setText(menuDetailBean.getDATE());
tv_TIME.setText(menuDetailBean.getTIME());
tv_MEMBER.setText(menuDetailBean.getMEMBER());
tv_ORDER_TYPE.setText(menuDetailBean.getORDER_TYPE());
menuitem = menuDetailBean.getMENUITEMS();
menulist = Arrays.asList(menuitem.split(","));
Log.e("meuitem", "" + menulist.size());
stringMenuList = new ArrayList<>();
for (int i = 0; i < menulist.size(); i++) {
StringMenuListBean stringMenu = new StringMenuListBean();
stringMenu.setName(menulist.get(i));
stringMenuList.add(stringMenu);
}
viewallAdapter = new ViewAllAdapter(getApplication(), stringMenuList);
rcyView_mymenu.setHasFixedSize(true);
rcyView_mymenu.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rcyView_mymenu.setAdapter(viewallAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_download:
Bitmap bitmap1 = loadBitmapFromView(ll_linear, ll_linear.getWidth(), ll_linear.getHeight());
saveBitmap(bitmap1);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/screenshotdemo.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), imagePath.getAbsolutePath() + "", Toast.LENGTH_SHORT).show();
boolean_save = true;
btn_download.setText("Check image");
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
}
this is my Activity and below is my Database Utility code in which i saved all cart item . i want every added item is shown in different activity with its whole information.public class DbUtils {
public static void saveCart(Context context, CartItemBean data) {
ContentValues value = new ContentValues();
// for (CartItemBean data : data1) {
value.put(DbConstants.COLUMN_PACKID, data.getCOLUMN_PACKID());
value.put(DbConstants.COLUMN_PACKAGENAME, data.getCOLUMN_PACKAGENAME());
value.put(DbConstants.COLUMN_SUBPACKAGEID, data.getCOLUMN_SUBPACKAGE_ID());
value.put(DbConstants.COLUMN_SUBPACKAGENAME, data.getCOLUMN_SUBPACKAGE_NAME());
value.put(DbConstants.COLUMN_USERID, data.getCOLUMN_USERID());
value.put(DbConstants.COLUMN_USER_NAME, data.getCOLUMN_USER_NAME());
value.put(DbConstants.COLUMN_CATID, data.getCOLUMN_CATID());
value.put(DbConstants.COLUMN_CATNAME, data.getCOLUMN_CATNAME());
value.put(DbConstants.COLUMN_MENUITEMS, data.getCOLUMN_MENUITEMS());
value.put(DbConstants.COLUMN_MENUID, data.getCOLUMN_MENUID());
value.put(DbConstants.COLUMN_MEMBER, data.getCOLUMN_MEMBER());
value.put(DbConstants.COLUMN_DATE, data.getCOLUMN_DATE());
value.put(DbConstants.COLUMN_TIME, data.getCOLUMN_TIME());
value.put(DbConstants.COLUMN_TOTAL_PRICE, data.getCOLUMN_TOTAL_PRICE());
value.put(DbConstants.COLUMN_ORDER_TYPE, data.getCOLUMN_ORDER_TYPE());
value.put(DbConstants.COLUMN_DISCOUNT, data.getCOLUMN_DISCOUNT());
value.put(DbConstants.COLUMN_CITY, data.getCOLUMN_CITY());
value.put(DbConstants.COLUMN_CURRENTDATE, data.getCOLUMN_CURRENT_DATE());
value.put(DbConstants.COLUMN_PRICE, data.getCOLUMN_PRICE());
value.put(DbConstants.COLUMN_PROMOCODE, data.getCOLUMN_PROMOCODE());
value.put(DbConstants.COLUMN_PAYMENT_STATUS, data.getCOLUMN_PAYMENT_STATUS());
DbAccesser.getInstance(context).insertIntoTable(value,
DbConstants.TABLE_CART);
// }
}
// get product list
public static ArrayList<CartItemBean> getCartItems(Context context) {
ArrayList<CartItemBean> offlineDataList = new ArrayList<CartItemBean>();
Cursor cursor = DbAccesser.getInstance(context).query(DbConstants.TABLE_CART, null, null,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
CartItemBean data = new CartItemBean();
data.setCOLUMN_ID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ID))));
data.setCOLUMN_CATID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATID))));
data.setCOLUMN_PAYMENT_STATUS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PAYMENT_STATUS))));
data.setCOLUMN_USER_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USER_NAME)))));
data.setCOLUMN_USERID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USERID))));
data.setCOLUMN_PACKAGENAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKAGENAME))));
data.setCOLUMN_CATNAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATNAME))));
data.setCOLUMN_CITY((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CITY))));
data.setCOLUMN_CURRENT_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CURRENTDATE))));
data.setCOLUMN_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DATE))));
data.setCOLUMN_DISCOUNT(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DISCOUNT)))));
data.setCOLUMN_MEMBER((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MEMBER))));
data.setCOLUMN_MENUITEMS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUITEMS))));
data.setCOLUMN_ORDER_TYPE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE))));
data.setCOLUMN_PACKID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKID))));
data.setCOLUMN_PROMOCODE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PROMOCODE))));
data.setCOLUMN_TIME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TIME)))));
data.setCOLUMN_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PRICE)))));
data.setCOLUMN_MENUID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUID)))));
data.setCOLUMN_TOTAL_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
data.setCOLUMN_SUBPACKAGE_ID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGEID)))));
data.setCOLUMN_SUBPACKAGE_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
offlineDataList.add(data);
cursor.moveToNext();
}
}
return offlineDataList;
}
public static MenuDetailBean getMenuDetail(Context context, String packId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + DbConstants.TABLE_CART + " WHERE "
+ DbConstants.COLUMN_PACKID + " = " + packId;
Cursor c = database.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
MenuDetailBean menuDetailBean = new MenuDetailBean();
menuDetailBean.setTIME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TIME)))));
menuDetailBean.setDATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_DATE)))));
menuDetailBean.setSUBPACKAGE_NAME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
menuDetailBean.setPRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_PRICE)))));
menuDetailBean.setTOTAL_PRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
menuDetailBean.setMEMBER(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MEMBER)))));
menuDetailBean.setORDER_TYPE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE)))));
menuDetailBean.setMENUITEMS(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MENUITEMS)))));
menuDetailBean.setCURRENT_DATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_CURRENTDATE)))));
return menuDetailBean;
}
public static int deteteTableData(Context context, String tableName) {
int status = 0;
status = DbAccesser.getInstance(context).deleteTable(tableName);
return status;
}
public static void deleteOrderAfterTEnDays(Context context) {
Cursor cursor = DbAccesser.getInstance(context).raw_query("delete from new_order where current_datetime < default current_timestamp - INTERVAL 10 DAY", null);
Log.e("CURSOR", "" + cursor);
}
// get bill by particular date and outletId
public static CartItemBean getOrderBillByOutlet(Context context, CartItemBean bean) {
CartItemBean cartItemBean = new CartItemBean();
String[] params = new String[]{bean.getCOLUMN_PACKID(), bean.getCOLUMN_MEMBER(), bean.getCOLUMN_DATE(), bean.getCOLUMN_TIME()};
Cursor cursor = DbAccesser.getInstance(context).raw_query("select column_id,name,SUM(order_billing) from cart where order_date=? AND outlets_id=?", params);
if (cursor != null) {
if (cursor.moveToFirst()) {
}
}
return cartItemBean;
}
public static void updateRetailerList(Context context, CartItemBean cartItemBean) {
ContentValues values = new ContentValues();
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
values.put(DbConstants.COLUMN_MEMBER, cartItemBean.getCOLUMN_MEMBER());
values.put(DbConstants.COLUMN_DATE, cartItemBean.getCOLUMN_DATE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TIME());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
values.put(DbConstants.COLUMN_SUBPACKAGEID, cartItemBean.getCOLUMN_SUBPACKAGE_ID());
values.put(DbConstants.COLUMN_SUBPACKAGENAME, cartItemBean.getCOLUMN_SUBPACKAGE_NAME());
values.put(DbConstants.COLUMN_CURRENTDATE, cartItemBean.getCOLUMN_CURRENT_DATE());
String sql2 = "UPDATE " + DbConstants.TABLE_CART + " SET " +
DbConstants.COLUMN_MEMBER + " = '" + cartItemBean.getCOLUMN_MEMBER() + "', "
+ DbConstants.COLUMN_DATE + " = '" + cartItemBean.getCOLUMN_DATE() + "', "
+ DbConstants.COLUMN_TIME + " = '" + cartItemBean.getCOLUMN_TIME() + "', "
+ DbConstants.COLUMN_SUBPACKAGEID + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_ID() + "', "
+ DbConstants.COLUMN_SUBPACKAGENAME + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_NAME() + "', "
+ DbConstants.COLUMN_CURRENTDATE + " = '" + cartItemBean.getCOLUMN_CURRENT_DATE() + "', "
+ DbConstants.COLUMN_TOTAL_PRICE + " = '" + cartItemBean.getCOLUMN_TOTAL_PRICE() + "' "
+ " WHERE " +
DbConstants.COLUMN_PACKID + " = '" + cartItemBean.getCOLUMN_PACKID() + "' AND "
+ DbConstants.COLUMN_USERID + " = '" + cartItemBean.getCOLUMN_USERID() + "'";
database.execSQL(sql2);
Log.e("UPDATE", sql2);
}
public static void deleteCartItem(Context context, String packId, String userId) {
DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
database.delete(DbConstants.TABLE_CART, DbConstants.COLUMN_PACKID + "=? AND "+ DbConstants.COLUMN_USERID + "=?", new String[]{packId, userId});
database.close();
}`
You can associate multiple items to each category, by creating a table with entries which each reflect an association.
For example, assuming you have a toy database like quoted at the end of this answer (see "MCVE foundation").
Create the table and add a few associations:
create table associations (id int, iid int);
insert into associations values (1, 1);
insert into associations values (1, 2);
insert into associations values (1, 3);
insert into associations values (2, 4);
insert into associations values (2, 5);
insert into associations values (3, 6);
insert into associations values (3, 7);
Then you can retrieve items for all categories:
select cat, name from cats inner join associations using(id) inner join items using (iid);
Output:
cat name
----------- ----------
soup tomato
soup sour
soup corn
namkeen katchori
namkeen aloo
stall tikija
stall patties
Or for more compact output:
select cat, group_concat(name, ', ')
from cats inner join
associations using(id) inner join
items using (iid)
group by cat
order by id;
Output:
cat group_concat(name, ', ')
----------- ------------------------
soup tomato, sour, corn
namkeen katchori, aloo
stall tikija, patties
I am not sure what you mean by "recycle view", maybe because I am working within pure SQLite (no other language, like you obviously use).
I hope one of the two representations suits you - or gets you on the way to achieve your goal.
MCVE foundation
(I did a .dump on my test environment, which I roughly cobbled together to demonstrate the idea. Please consider doing something like this for your next question involving SQLite. That makes it easier for the answerer and thereby faster for you. It also probably gets you a tighter fit of solution and often prevents misunderstandings.
Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? if you like.):
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE table_1 (a int, b int, c int);
INSERT INTO table_1(a,b,c) VALUES(1,5,7);
INSERT INTO table_1(a,b,c) VALUES(2,10,14);
CREATE TABLE table_2 (a int, c int);
INSERT INTO table_2(a,c) VALUES(3,11);
INSERT INTO table_2(a,c) VALUES(6,22);
CREATE TABLE cats (id int, cat varchar(20));
INSERT INTO cats(id,cat) VALUES(1,'soup');
INSERT INTO cats(id,cat) VALUES(2,'namkeen');
INSERT INTO cats(id,cat) VALUES(3,'stall');
CREATE TABLE items (iid int, name varchar(20));
INSERT INTO items(iid,name) VALUES(1,'tomato');
INSERT INTO items(iid,name) VALUES(2,'sour');
INSERT INTO items(iid,name) VALUES(3,'corn');
INSERT INTO items(iid,name) VALUES(4,'katchori');
INSERT INTO items(iid,name) VALUES(5,'aloo');
INSERT INTO items(iid,name) VALUES(6,'tikija');
INSERT INTO items(iid,name) VALUES(7,'patties');
COMMIT;
I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());