I have column which is supposed to contain the true and false value in db. I understand that they should be in form of 0 and 1. I have an int column "status" but it always returns zero.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "( "
+ "ID INTEGER PRIMARY KEY ,"
+ VALUE + " TEXT NOT NULL, "
+ STATUS + " INTEGER NOT NULL)";
db.execSQL(create_table);
}
public int getStatus(String _id,int status)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + STATUS + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {_id});
if(cursor.moveToFirst()){
return cursor.getInt(cursor.getColumnIndex(STATUS));
} else {
return 0;
}
}
I need to set to true in the case below but item_status returns zero everytime. I checked the db and there is NULL in the whole status column.
if (success) {
status = 1;
int item_status = db.getStatus(fetchId(),status);
Toast.makeText(this, " item_status " + item_status , Toast.LENGTH_SHORT).show();
}
Related
I have a JPA Entity with a large number of fields and millions of records. For a report, I need only some of the fields. So I want to create an Object with the essential fields due to resource constraints. I tried to create a list of new objects in JPQL. It gives only one object as a result, where multiple objects are expected.
String j;
j = "select new lk.gov.health.phsp.pojcs.ClientEncounterComponentBasicDataToQuery("
+ "f.name, "
+ "f.code, "
+ "f.item.code, "
+ "f.shortTextValue, "
+ "f.integerNumberValue, "
+ "f.longNumberValue, "
+ "f.realNumberValue, "
+ "f.booleanValue, "
+ "f.dateValue, "
+ "f.itemValue.code"
+ ") ";
j += " from ClientEncounterComponentItem f "
+ " where f.retired=false "
+ " and f.encounter.id=:eid";
Map m = new HashMap();
m.put("eid", endId);
The EBJ is as follows.
public List<Object> findObjects(String jpql, Map<String, Object> parameters, TemporalType tt) {
TypedQuery<Object> qry = getEntityManager().createQuery(jpql, Object.class);
Set s = parameters.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
Object pVal = m.getValue();
String pPara = (String) m.getKey();
if (pVal instanceof Date) {
Date pDate = (Date) pVal;
qry.setParameter(pPara, pDate, TemporalType.DATE);
} else {
qry.setParameter(pPara, pVal);
}
}
try {
return qry.getResultList();
} catch (Exception e) {
return null;
}
}
What am I doing wrong? I am using EclipseLink as the persistence provider.
I've set up an SQL database and used 'Date' as my column header which obviously has its own format as opposed to integer or char etc. However when I put in a date such as 2/11/2016 it gives me the error message - 'DATE' cannot hold values of type 'INTEGER'. Does anyone know what code I should be using? Here's my jsp below. All goes into DB when I remove all reference to date.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(" + tableNum + "," + "'" + firstName + "'" + "," + "'" + lastName + "'" + "," + "'" + Address + "'" + "," + Phone + "," + date + "," + People +")";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
I implement an Activity which contains a NavigationView with includes several fragments. The first Fragment of the NavigationView contains a RecyclerView with a TabLayout, so that I can swipe between the different lists. Because I've got always the same list(UI) with different values, I decided to implement only one Fragment with a newInstance().
My problem now is that the list does not update properly when I jump from Tab1 to Tab2 or if I change a list item and come back to the list. Can somebody help me? I can't figure it out ...
swipe from Tab1 to Tab2
This is my fragment which contains the RecyclerView:
public class HinweiseFragment extends Fragment {
private static final String TAG = "HinweiseFragment";
private TabLayout mTabLayout;
private ViewPager mViewPager;
private HinweiseTabAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).getSupportActionBar().setTitle("Hinweise");
((MainActivity) getActivity()).showFloatingActionButton();
View rootView = inflater.inflate(R.layout.fragment_hinweise, null);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tablayout_hinweise);
mTabLayout.addTab(mTabLayout.newTab().setText("BESAMUNG"));
mTabLayout.addTab(mTabLayout.newTab().setText("NICHT BESAMEN"));
mTabLayout.addTab(mTabLayout.newTab().setText("VERDACHT"));
mTabLayout.addTab(mTabLayout.newTab().setText("ALLE"));
mTabLayout.setTabGravity(mTabLayout.GRAVITY_FILL);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager_hinweise);
adapter = new HinweiseTabAdapter(getChildFragmentManager(), mTabLayout.getTabCount(), getContext());
mViewPager.setAdapter(adapter);
mViewPager.setOffscreenPageLimit(3);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition(), true);
adapter.refreshFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootView;
}
}
This is my TabAdapter:
public class HinweiseTabAdapter extends FragmentPagerAdapter {
HinweiseListFragment tab_besamung, tab_nicht, tab_verdacht, tab_alle;
String[] tabHostTitle = {"BESAMUNG", "NICHT BESAMEN", "VERDACHT", "ALLE"};
int mNumOfTabs;
private final Context mContext;
public HinweiseTabAdapter(FragmentManager fm, int NumOfTabs, Context context) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
tab_besamung = HinweiseListFragment.newInstance(0, "BESAMUNG");
return tab_besamung;
case 1:
tab_nicht = HinweiseListFragment.newInstance(1, "NICHT BESAMEN");
return tab_nicht;
case 2:
tab_verdacht = HinweiseListFragment.newInstance(2, "VERDACHT");
return tab_verdacht;
case 3:
tab_alle = HinweiseListFragment.newInstance(3, "ALLE");
return tab_alle;
default:
return null;
}
}
public void refreshFragment(int position) {
switch (position) {
case 0:
tab_besamung.update();
break;
case 1:
tab_nicht.update();
break;
case 2:
tab_verdacht.update();
break;
case 3:
tab_alle.update();
break;
}
}
#Override
public int getItemPosition(Object object) {
int position = getItemPosition(object);
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return tabHostTitle[position];
}
}
and this is my Fragment which contains the List:
public static HinweiseListFragment newInstance(int page, String title) {
HinweiseListFragment fragment = new HinweiseListFragment();
Bundle args = new Bundle();
args.putInt(PASSED_PAGE, page);
args.putString(PASSED_TITLE, title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
tabCount = args.getInt(PASSED_PAGE);
tabName = args.getString(PASSED_TITLE);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hinweise_list, container, false);
list_hinweise = new ArrayList<>();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_listHinweise);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeHinweise);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
refreshContent();
}
});
}
});
db = new DataBase(getActivity());
userHitKdr();
List<String> tab_ = db.getAll("SELECT * from tab_info where user_tab ='" + userdb + "' ");
if (tab_.size() != 2) {
db.updateSql("delete from tab_info where user_tab='" + userdb + "' ");
db.updateSql("insert into tab_info (activity_tab,tab_select,user_tab) values ('home','0','" + userdb + "'),('aufgabe','0','" + userdb + "'); ");
} else {
}
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mHinweiseAdapter = new HinweiseAdapter(getActivity(), getHinweise());
mRecyclerView.setAdapter(mHinweiseAdapter);
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
Intent detailView = new Intent(getActivity(), HinweiseDetail.class);
String[] tierarr = new String[tier_id.size()];
tier_id.toArray(tierarr);
String[] hinarr = new String[hin_id.size()];
hin_id.toArray(hinarr);
detailView.putExtra("detailart", "ovalert");
detailView.putExtra("idTier", tier_id.get(position));
detailView.putExtra("idDetail", hin_id.get(position));
int ipos = position;
Integer integerConverter = new Integer(ipos);
String s = integerConverter.toString();
detailView.putExtra("pos", s);
detailView.putExtra("arrIdTier", tierarr);
detailView.putExtra("arrIdHin", hinarr);
detailView.putExtra("userDetail", userdb);
detailView.putExtra("hitDetail", hitdb);
startActivity(detailView);
}
});
return rootView;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if(list_hinweise != null) {
update();
}
}
}
public String checkTab(int tab) {
tabCount = tab;
//tabName = name;
if (tabCount == 0) {
auswahl = " animalReproductionIndication.off='0' and (animalReproductionIndication.indicationCertainty ='IN' or animalReproductionIndication.indicationCertainty ='ID' or animalReproductionIndication.indicationCertainty ='' ) and ";
db.updateSql("update tab_info set tab_select='" + tabCount + "' where activity_tab='home' and user_tab='" + userdb + "' ");
if (list_hinweise != null) {
list_hinweise.clear();
if (mHinweiseAdapter != null) {
mHinweiseAdapter.notifyDataSetChanged();
}
}
}
if (tabCount == 1) {
auswahl = " animalReproductionIndication.off='0' and (animalReproductionIndication.indicationCertainty ='NI' or animalReproductionIndication.indicationCertainty ='HO') and ";
db.updateSql("update tab_info set tab_select='" + tabCount + "' where activity_tab='home' and user_tab='" + userdb + "' ");
if (list_hinweise != null) {
list_hinweise.clear();
if (mHinweiseAdapter != null) {
mHinweiseAdapter.notifyDataSetChanged();
}
}
}
if (tabCount == 2) {
auswahl = " animalReproductionIndication.off='0' and animalReproductionIndication.indicationCertainty ='SU' and ";
db.updateSql("update tab_info set tab_select='" + tabCount + "' where activity_tab='home' and user_tab='" + userdb + "' ");
if (list_hinweise != null) {
list_hinweise.clear();
if (mHinweiseAdapter != null) {
mHinweiseAdapter.notifyDataSetChanged();
}
}
}
if (tabCount == 3) {
auswahl = " animalReproductionIndication.off='0' and (animalReproductionIndication.indicationCertainty ='IN' or animalReproductionIndication.indicationCertainty ='NI' or animalReproductionIndication.indicationCertainty ='SU' or animalReproductionIndication.indicationCertainty ='ID' or animalReproductionIndication.indicationCertainty ='HO') and ";
db.updateSql("update tab_info set tab_select='" + tabCount + "' where activity_tab='home' and user_tab='" + userdb + "' ");
if (list_hinweise != null) {
list_hinweise.clear();
if (mHinweiseAdapter != null) {
mHinweiseAdapter.notifyDataSetChanged();
}
}
}
return auswahl;
}
public void update(){
tabCount = getArguments() != null ? getArguments().getInt(PASSED_PAGE) : 0;
tabName = getArguments() != null ? getArguments().getString(PASSED_TITLE) : "BESAMUNG";
list_hinweise.clear();
mHinweiseAdapter = new HinweiseAdapter(getActivity(), getHinweise());
mRecyclerView.setAdapter(mHinweiseAdapter);
}
public void refreshContent() {
importIndication();
tabCount = getArguments() != null ? getArguments().getInt(PASSED_PAGE) : 0;
tabName = getArguments() != null ? getArguments().getString(PASSED_TITLE) : "BESAMUNG";
list_hinweise.clear();
mHinweiseAdapter = new HinweiseAdapter(getActivity(), getHinweise());
mRecyclerView.setAdapter(mHinweiseAdapter);
// stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
private List<ListHinweise> getHinweise() {
checkTab(tabCount);
tm = new DateTime();
rg = new DateRegex();
tt = new DateTime();
try {
db.checkAndCopyDatabase();
db.openDatabase();
} catch (SQLiteException e) {
e.printStackTrace();
}
String sqlSortName = "select nameCode from sortieren where art='1' and (disable='0' or disable='1') and user='" + userdb + "' group by nameCode ";
String sqlSortDisable = "select disable from sortieren where art='1' and (disable='0' or disable='1') and user='" + userdb + "' group by nameCode ";
List<String> listSortName = db.getAll(sqlSortName);
List<String> listSortDisable = db.getAll(sqlSortDisable);
String sortSql = "";
for (int s1 = 0; s1 < listSortName.size(); s1++) {
System.out.println("Sort: " + listSortDisable.get(s1));
if (s1 == listSortName.size() - 1) {
String orderby = " desc ";
if (listSortDisable.get(s1).equals("0"))
orderby = " asc ";
if (listSortName.get(s1).equals("indicationDateTime"))
sortSql = sortSql + " animalReproductionIndication." + listSortName.get(s1) + " " + orderby;
else if (listSortName.get(s1).equals("farmersAnimalNr"))
sortSql = sortSql + " cast(OVALERTAPP." + listSortName.get(s1) + " as integer) " + orderby;
else
sortSql = sortSql + " OVALERTAPP." + listSortName.get(s1) + " " + orderby;
} else {
String orderby = " desc ,";
if (listSortDisable.get(s1).equals("0"))
orderby = " asc ,";
if (listSortName.get(s1).equals("indicationDateTime"))
sortSql = sortSql + " animalReproductionIndication." + listSortName.get(s1) + " " + orderby;
else if (listSortName.get(s1).equals("farmersAnimalNr"))
sortSql = sortSql + " cast(OVALERTAPP." + listSortName.get(s1) + " as integer) " + orderby;
else
sortSql = sortSql + " OVALERTAPP." + listSortName.get(s1) + " " + orderby;
}
}
String sxc = sortSql;
sxc = sxc.trim();
if (!sxc.equals(""))
sortSql = " order by " + sortSql;
System.out.println("Sort: " + sortSql);
try {
sql = " FROM OVALERTAPP, animalReproductionIndication WHERE " + sql_user_hit + " OVALERTAPP.AnimalNumber= animalReproductionIndication.AnimalNumber and " + auswahl + "1 " + sortSql;
String prio = db.getSelect("select nameCode from primaeridentifikation where user='" + userdb + "' and art='1' and disable='1' ");
List<String> einstellung_name = db.getAll("SELECT name from einstellungen where user ='" + userdb + "' and seite='1' and disable='1' ");
List<String> einstellung_nameCode = db.getAll("SELECT nameCode from einstellungen where user ='" + userdb + "' and seite='1' and disable='1' ");
String xxInhalt = " ";
for (int xx = 0; xx < einstellung_name.size(); xx++) {
String namexx = einstellung_name.get(xx);
for (int yy = 0; yy < namexx_.length; yy++) {
namexx = namexx.replace(namexx_[yy], Abkxx_[yy]);
}
xxInhalt = xxInhalt + "' " + namexx + ": ' || OVALERTAPP." + einstellung_nameCode.get(xx) + " ||";
}
xxInhalt = " || '<br>' || " + xxInhalt + " ''";
xxInhalt = xxInhalt.replace("OVALERTAPP.participantAnimal", "OVALERTAPP.participantAnimalNr");
if (einstellung_name.size() < 1) {
xxInhalt = " ";
}
tier_id = db.getAll("SELECT OVALERTAPP.id " + sql);
hin_id = db.getAll("SELECT animalReproductionIndication.id " + sql);
hin_besamt = db.getAll("SELECT animalReproductionIndication.indicationCertainty " + sql);
hin_blaue = db.getAll("select animalReproductionIndication.showType " + sql);
hin_time = db.getAll("select animalReproductionIndication.indicationDateTime " + sql); //gesehen
if (prio.equals("")) {
String sql_ = " SELECT OVALERTAPP.AnimalNumber || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql; // time
sql_ = sql_.replace("OVALERTAPP.aktivseit", "animalReproductionIndication.indicationDateTime");
hin_info = db.getAll(sql_);
// hin_info = db.getAll(" SELECT OVALERTAPP.AnimalNumber || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql); // time
System.out.println(" SELECT OVALERTAPP.AnimalNumber || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql); // time
} else {
//hin_info = db.getAll(" SELECT OVALERTAPP." + prio + " || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql); // time
String sql_ = " SELECT OVALERTAPP." + prio + " || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql; // time
sql_ = sql_.replace("OVALERTAPP.aktivseit", "animalReproductionIndication.indicationDateTime");
hin_info = db.getAll(sql_);
System.out.println(" SELECT OVALERTAPP." + prio + " || ' I.H: ' || '--' || ' T I.B: ' || OVALERTAPP.lastInseminationDate || ' T LT: ' || OVALERTAPP.calvingDate || ' T '|| reproductionStatus " + xxInhalt + " " + sql); // time
}
for (int i = 0; i < hin_besamt.size(); i++) {
String timehin = db.getSelect("SELECT indicationDateTime FROM animalReproductionIndication where animalReproductionIndication.id=" + hin_id.get(i));
String animalhin = db.getSelect("SELECT animalNumber FROM animalReproductionIndication where animalReproductionIndication.id=" + hin_id.get(i));
// List<String> maxList=db.getAll("SELECT indicationDateTime FROM animalReproductionIndication where user='"+userdb+"' and animalNumber='"+animalhin+"' and indicationDateTime!='"+timehin+"' and indicationExpirationDateTime !='' order by indicationDateTime desc ");
String timehin_date = timehin + " ";
List<String> maxList = db.getAll("SELECT indicationDateTimeHin FROM animalReproductionIndicationHinweise where userHin='" + userdb + "' and animalNumberHin='" + animalhin + "' and indicationDateTimeHin!='" + timehin + "' and (indicationDateTimeHin not LIKE '" + timehin_date.substring(0, 8) + "%') and indicationDateTimeHin < '" + timehin + "' order by indicationDateTimeHin desc ");
String hin = "";
if (maxList.size() > 0) {
hin = maxList.get(0);
System.out.println("hin++++" + hin + " neue: " + timehin);
}
//hin=tm.getDayToDay(hin,"yyyyMMddkkmmss");
hin = tm.getDayMinusDayDate(hin, timehin);
String line = statusUmbenennen(hin_info.get(i));
System.out.println("line: " + line);
String info_ = statusUmbenennen(hin_info.get(i));
System.out.println("line1: " + line);
info_ = info_.replace("--", hin);
System.out.println("line2: " + info_);
System.out.println(info_);
String[] anfang = {"I Kalb: ", "I Bes: ", "n Kalb: ", "I Bru: ", " Trocken: "};
String[] end = {"", "", "", "", ""};
String[] anfang1 = {"I.H: ", "I.B: ", "LT: "};
String[] end1 = {"", "", ""};
try {
info_ = lineYMDTag(info_, anfang1, end1);
System.out.println("line3: " + info_);
} catch (ParseException e) {
e.printStackTrace();
}
String[] anfangx = {"Aktiv seit: "};
String[] endx = {""};
try {
info_ = lineYMDHMS(info_, anfangx, endx);
} catch (ParseException e) {
e.printStackTrace();
}
try {
info_ = lineYMD(info_, anfang, end);
System.out.println("line4: " + info_);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("info_: " + info_);
ListHinweise item = new ListHinweise();
item.setHinId(tier_id.get(i));
item.setHinId(hin_id.get(i));
item.setHinBlaue(hin_blaue.get(i));
item.setHinInfo(info_);
item.setHinBesamt(hin_besamt.get(i));
System.out.println(hin_time.get(i) + "_xmmx_" + tt.getHourDiffStartToNow(hin_time.get(i), "yyyyMMddkkmmss"));
item.setHinTime(String.valueOf(tt.getHourDiffStartToNow(hin_time.get(i), "yyyyMMddkkmmss")));
list_hinweise.add(item);
db.close();
}
} catch (SQLiteException e) {
e.printStackTrace();
}
return list_hinweise;
}
I have already tried to update the list with onResume or setUserVisibleHint but without success. My refreshContent() method works fine, but I want to update the list automatically and not manually. If I took the onResume() method the Items will be refreshed but then my Tab1 contains the values from Tab1 and Tab2.
I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)
The following code executes successfully and the return value of cmd.ExecuteNonQuery returns 1 indicating the row was successfully updated but the database is not truly updated. How could that be? I'm using sqlserver2008.
public string updatePost(string id, string head, string body)
{
connection = new SqlConnection(connString);
string cmdStr = "update News set Header = '"+head+"' , [Text] = '"+body+"' where Id = "+int.Parse(id)+"";
string msg = String.Empty;
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdStr, connection);
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:"+id+"' was successfully updated. Rows effected:"+effected+"";
}
catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
finally
{
connection.Close();
}
return msg;
}
Try this, this fixes some problems (like sql-injection), perhaps also your update issue:
public string UpdatePost(string id, string head, string body)
{
string msg = "";
string cmdStr = "update News set Header = #header, [Text] = #body where Id = #id";
using (var con = new SqlConnection(connString))
{
try
{
con.Open();
using (var cmd = new SqlCommand(cmdStr, con))
{
cmd.Parameters.AddWithValue("#header", head);
cmd.Parameters.AddWithValue("#body", body);
cmd.Parameters.AddWithValue("#id", int.Parse(id));
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:" + id + "' was successfully updated. Rows effected:" + effected + "";
}
} catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
}
return msg;
}