How to solve a TabLayout inside a Fragment which includes four Tabs created by one Fragment with newInstance() using RecyclerView - fragment

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.

Related

Splitting a string Value into chunks of a certain size

public static void SplittingStringIntoChunksCounts(string InputValue)
{
int ChunkSize = 5;
InputValue = "TestingManualTestingAutomTesting";
Dictionary<string, int> dictValue = new Dictionary<string, int>();
for (int i = 0; i < InputValue.Length; i += chunkSize)
{
if (i + chunkSize <= InputValue.Length)
{
Console.WriteLine(InputValue.Substring(i, chunkSize));
string tempValue = InputValue.Substring(i, chunkSize);
if (dictValue.ContainsKey(tempValue))
//if (!dictValue.ContainsKey(tempValue))
{
dictValue[tempValue]++;
//dictValue[tempValue] = 0;
}
else { dictValue[tempValue] = 1; }
// dictValue[tempValue]++;
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}
}
foreach (var item in dictValue)
{
Console.WriteLine("Input User== " + " " + item.Key + " " + "Number of Time" + " " + item.Value);
}

How can update contact in existing contact update to postal address

This is my code to existing contact to change the postal address code
ops = new ArrayList<ContentProviderOperation>();
rawContactID = ops.size();
///Insert code are working/////
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,addr)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtcity.getText().toString())
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtpostcode.getText().toString())
enter code here
`enter code here` .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtcountry.getText().toString()).build());
//// I am trying this update record code but not working///
btn_upcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, addr)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, scity)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, scode)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,scountry)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I am update the record coding to btn_upcontacts listner but not working,Please Help me
I am trying the many code use are but not working
I have a simply edit the text andd update to the exsiting contact the postal address without the sqllite datbase
Advance in Thanks
int _contact_id = 10110; // your Conatct id
Uri rawContactUri = null;
Cursor rawContactCursor = null;
try {
// if some fields not available use rawContactUri as ID
rawContactUri = null;
rawContactCursor = context.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts._ID},
ContactsContract.RawContacts.CONTACT_ID + " = " + _contact_id,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rawContactCursor != null) {
rawContactCursor.close();
}
}
Boolean noAddress = true;
Cursor currAddr = null;
try {
Uri URI_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE + " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[]{
String.valueOf(_contact_id),
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
currAddr = context.getContentResolver().query(URI_ADDRESS, null, SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
if (currAddr.getCount() > 0) {
currAddr.moveToFirst();
while (!currAddr.isAfterLast()) {
noAddress = false;
currAddr.moveToNext();
}
} else {
noAddress = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (currAddr != null) {
currAddr.close();
}
}
if (noAddress) {
// address is not available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ContentValues adrsValues = new ContentValues();
adrsValues.put(ContactsContract.Data.RAW_CONTACT_ID, ContentUris.parseId(rawContactUri));
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, "1");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name);
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "");
adrsValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, adrsValues);
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
} else {
// address is already available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where1, AryStructuredAdd1)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "")
.build());
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
}

Select results truncated without error message

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)

How do you append text in CodeMirror

I know you use
editor.setValue("");
to set one value but how do you append in CodeMirror?
IE:
editor.appendText();?
Use replaceRange. For example editor.replaceRange(myString, CodeMirror.Pos(editor.lastLine())). Re-setting the entire editor is needlessly expensive.
Here is a little script I wrote to add code to any editor (in Joomla):
function addCodeToEditor(code_string, editor_id, merge, merge_target){
if (Joomla.editors.instances.hasOwnProperty(editor_id)) {
var old_code_string = Joomla.editors.instances[editor_id].getValue();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
Joomla.editors.instances[editor_id].setValue(_string.trim());
return true;
}
} else {
Joomla.editors.instances[editor_id].setValue(code_string.trim());
return true;
}
} else {
var old_code_string = jQuery('textarea#'+editor_id).val();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
jQuery('textarea#'+editor_id).val(_string.trim());
return true;
}
} else {
jQuery('textarea#'+editor_id).val(code_string.trim());
return true;
}
}
return false;
}
The advantage it this script is you can work with multiple editors on the page.

excel data uploading is not working in sql database

This is pradeep
This is the code of the excel uploading to sql database
protected void btnupload_Click ( object sender, EventArgs e )
{
//string name = ddloutlet.SelectedValue.ToString ();
//cal
try
{
System.IO.FileInfo file = new System.IO.FileInfo(fileupload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length), file.Extension.Length);
fname = fname + DateTime.Now.ToString("_ddMMyyyy_HHmmss") + file.Extension;
fileupload1.PostedFile.SaveAs(Server.MapPath("locations/") + fname);
string filexetion = file.Extension;
if ( filexetion == ".xlsx" )
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
}
else if ( filexetion == ".xls" )
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes; \"";
}
OleDbConnection connection = new OleDbConnection(excelConnectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
SqlConnection conn = new SqlConnection(strconnection);
conn.Open();
try
{
if (dr.Read() == true)
{
while (dr.Read())
{
string locationname = dr["Location Name"].ToString();
string status = dr["Status"].ToString();
if (locationname != "" && status != "")
{
string query = " select locationname from tbllocations where locationname='" + locationname + "' and outletid='" + Session["outlet_id"].ToString() + "'";
// conn.Open();
SqlCommand cmdquery = new SqlCommand(query, conn);
SqlDataReader drreader;
drreader = cmdquery.ExecuteReader();
if (drreader.Read())
{
c = true;
ssss = ssss + locationname + ",";
// ss = ssss.Split(',');
}
else
{
drreader.Close();
string qryprduct = "insert into tbllocations(locationname,status,outletid,cityid)values('" + locationname + "','" + status + "','" + Session["outlet_id"].ToString() + "','" + Session["cityid"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(qryprduct, conn);
conn.Close();
conn.Open();
cmd1.ExecuteNonQuery();
lblerror1.Visible = true;
lblerror1.Text = "Locations uploaded Sucess";
//conn.Close();
}
drreader.Close();
}
}
// connection.Close (); conn.Close ();
}
else
{
lblerror1.Text = "There is a empty excel sheet file,plz check";
lblerror1.Visible = true;
}
}
catch (Exception ex)
{
lblerror1.Visible = true;
lblerror1.Text = "Plz check the excel file formate";
}
finally
{
connection.Close(); conn.Close();
bind();
if (c == true)
{
lblerror1.Visible = true;
lblerror1.Text = "In excel this loactions are already exist. Please check,";
//for (int i = 0; i < ss.Length; i++)
//{
lblerror3.Visible = true;
lblerror3.Text = ssss;
//}
}
}
}
catch
{
}
}
The above code uploading is working but in excel 1st record is not uploading ,please tell me the what is the problem and give me suggestion please.
excel data is
Location Name Status
test1 1
test2 1
test3 1
test4 0
test5 1
test6 0
test7 1
test8 0
test9 1
test10 1
Thanks
Pradeep
You need to remove the
if (dr.Read() == true)
because it is immediately followed by a
while (dr.Read())
Each of these will read a record and the first one will skip the first row of the file