AEM CQ5 Query builder Multiple Path with Multiple Properties Issue - aem

Now am facing issue in Querybuilder api while trying with Multiple Path with Multiple Properties.
Code is attached here what I did. It is working fine one path with multiple properties and multiple path with one property. My requirement is like multiple path with multiple properties and also some predicates
suggestion would be appreciated
Map<String, String> map = new HashMap<String, String>();
ArrayList<Predicate> group = new ArrayList<Predicate>();
JSONArray jsonArray = new JSONArray();
if (null != searchPathList && searchPathList.size() > 0) {
mapCount = searchPathList.size();
for (int i = 0; i < searchPathList.size(); i++) {
//map.put("group." + (i + 1) + "_path", searchPathList.get(i));
}
}
// group.add(new Predicate("mypath1").set("path", "/content/opinion/columns"));
// group.add(new Predicate("mypath2").set("path", "/content/opinion/books"));
map.put("group.1_path","/content/opinion/columns");
map.put("group.2_path","/content/opinion/books");
map.put("type", CQJCRConstants.JCRPRIMARYTYPEPAGE);
//combine this group with OR
map.put("group.p.or", "true");
map.put("p.offset", "0");
map.put("p.hits", "full");
if (!TheCommonUtility.isEmpty(searchKeyWord)) {
/* map.put("group." + (mapCount + 1) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 1) + "_fulltext.relPath", "jcr:content/#jcr:title");
map.put("group." + (mapCount + 2) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 2) + "_fulltext.relPath", "jcr:content/#jcr:description");
map.put("group." + (mapCount + 3) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 3) + "_fulltext.relPath", "jcr:content/#cq:tags");
map.put("group." + (mapCount + 4) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 4) + "_fulltext.relPath", "jcr:content/#authorName");
map.put("group." + (mapCount + 5) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 5) + "_fulltext.relPath", "jcr:content/#SlugName");
PredicateGroup searchpathgroup = new PredicateGroup("path");
searchpathgroup.setAllRequired(false);
searchpathgroup.add(new Predicate("mypath1").set("path", "/content/opinion/columns"));
searchpathgroup.add(new Predicate("mypath2").set("path", "/content/opinion/books"));
*/
PredicateGroup searchKeyWordgroup = new PredicateGroup("property");
searchKeyWordgroup.setAllRequired(false);
Predicate titleskPredicate = new Predicate("title");
titleskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
titleskPredicate.set("property", "fn:lower-case(#" + "jcr:content/jcr:title");
titleskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(titleskPredicate);
Predicate desskPredicate = new Predicate("description");
desskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
desskPredicate.set("property", "fn:lower-case(#" + "jcr:content/jcr:description");
desskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(desskPredicate);
Predicate tagskPredicate = new Predicate("tagssk");
tagskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
tagskPredicate.set("property", "fn:lower-case(#" + "jcr:content/cq:tags");
tagskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(tagskPredicate);
Predicate authorNameskPredicate = new Predicate("authorNameSk");
authorNameskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
authorNameskPredicate.set("property", "fn:lower-case(#" + JcrConstants.JCR_CONTENT + "/" + "authorName"
+ ")");
authorNameskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(authorNameskPredicate);
Predicate slugskPredicate = new Predicate("SlugName");
slugskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
slugskPredicate.set("property", "fn:lower-case(#" + "jcr:content/SlugName");
slugskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(slugskPredicate);
group.add(searchKeyWordgroup);
}
Predicate notPredicate = new Predicate("hideInNav", "property");
notPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_NOT);
notPredicate.set("property", JcrConstants.JCR_CONTENT + "/" + "hideInNav");
notPredicate.set("value", "true");
group.add(notPredicate);
Predicate notMasterTitlePredicate = new Predicate("pageMasterNot", "property");
notMasterTitlePredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_UNEQUALS);
notMasterTitlePredicate.set("property", JcrConstants.JCR_CONTENT + "/" + JcrConstants.JCR_TITLE);
notMasterTitlePredicate.set("value", "Master Article");
group.add(notMasterTitlePredicate);
if (!ThecommonUtility.isEmpty(author)) {
Predicate authorNamePredicate = new Predicate("authorName", "property");
authorNamePredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
authorNamePredicate
.set("property", "fn:lower-case(#" + JcrConstants.JCR_CONTENT + "/" + "authorName" + ")");
authorNamePredicate.set("value", "%" + author.toLowerCase() + "%");
group.add(authorNamePredicate);
}
if (!ThecommonUtility.isEmpty(tagId)) {
Predicate tagPredecate = new Predicate("tags", "tagid");
tagPredecate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
tagPredecate.set(JcrPropertyPredicateEvaluator.PROPERTY, JcrConstants.JCR_CONTENT + "/" + "cq:tags");
tagPredecate.set("1_" + JcrPropertyPredicateEvaluator.VALUE, tagId);
group.add(tagPredecate);
}
if (!ThecommonUtility.isEmpty(start_time) && !ThecommonUtility.isEmpty(end_time)) {
final Predicate createdDatePredicate = new Predicate("issueDate", "daterange");
createdDatePredicate.set("property", JcrConstants.JCR_CONTENT + "/" + CQJCRConstants.ISSUEDATE);
createdDatePredicate.set("lowerBound", start_time);
createdDatePredicate.set("lowerOperation", ">=");
createdDatePredicate.set("upperBound", end_time);
createdDatePredicate.set("upperOperation", "<=");
group.add(createdDatePredicate);
}
if (!ThecommonUtility.isEmpty(order_by) && order_by.equalsIgnoreCase("cq:lastModified")) {
final Predicate orderByPredicate = new Predicate("orderBy", Predicate.ORDER_BY);
orderByPredicate.set(Predicate.ORDER_BY, "#" + JcrConstants.JCR_CONTENT + "/" + order_by);
orderByPredicate.set("orderby.index", "true");
orderByPredicate.set(Predicate.PARAM_SORT, Predicate.SORT_DESCENDING);
group.add(orderByPredicate);
} else if (!ThecommonUtility.isEmpty(order_by) && order_by.equalsIgnoreCase("oldest")) {
final Predicate orderByPredicate = new Predicate("orderBy", Predicate.ORDER_BY);
orderByPredicate.set(Predicate.ORDER_BY, "#" + JcrConstants.JCR_CONTENT + "/" + order_by);
orderByPredicate.set("orderby.index", "true");
orderByPredicate.set(Predicate.PARAM_SORT, Predicate.SORT_ASCENDING);
group.add(orderByPredicate);
}
try {
session = request.getResourceResolver().adaptTo(Session.class);
Query query = qbuilder.createQuery(PredicateGroup.create(map), session);
for (Predicate p : group) {
query.getPredicates().add(p);
}
query.setExcerpt(true);
query.setStart(startHit);
query.setHitsPerPage(showMoreCount);
result = query.getResult();

Solution : map.put("group.p.or", "true"); put this code in top and use PredicateGroup concept for search path {group=group: or=true[
{3_fulltext=fulltext: relPath=jcr:content/#jcr:title, fulltext=bibi}
{4_fulltext=fulltext: relPath=jcr:content/#jcr:description, fulltext=bibi}
{5_fulltext=fulltext: relPath=jcr:content/#cq:tags, fulltext=bibi}
{6_fulltext=fulltext: relPath=jcr:content/#authorName, fulltext=bibi}
{7_fulltext=fulltext: relPath=jcr:content/#weekSlugName, fulltext=bibi}
]}
{type=type: type=cq:Page}
{path=group: or=true[
{1_mypath1=mypath1: path=/content/week/opinion/columns}
{2_mypath2=mypath2: path=/content/week/opinion/books}
]}
{hideInNav=property: operation=not, value=true, property=jcr:content/hideInNav}
{pageMasterNot=property: operation=unequals, value=Master Article, property=jcr:content/jcr:title}
{authorName=property: operation=like, value=%ajish%, property=fn:lower-case(#jcr:content/authorName)}
{orderBy=orderby: orderby.index=true, sort=desc, orderby=#jcr:content/cq:lastModified}

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 to insert same id after insert update in c#

I'm trying to create an attendance project. I'm using update & insert in my code. Please check my code below. I know I'm vulnerable to SQL injection.
My problem is when I tried to Time In using the same ID even if I use that same ID for time out, it displays the time out not time-in. Any idea how I can time in again using same ID?
MySqlCommand cmd = new MySqlCommand("SELECT * FROM tbl_student_list INNER JOIN attendance_tbl On tbl_student_list.ID = attendance_tbl.stud_id WHERE stud_id ='" + dataGridView1.Rows[i].Cells["Column1"].Value + "'", conn);
cmd.Parameters.AddWithValue("stud_id", dataGridView1.Rows[i].Cells["Column1"].Value);
conn.Open();
MySqlDataReader DataRead = cmd.ExecuteReader();
DataRead.Read();
This is my Update Code:
//If already Time-In execute Time-Out
if (DataRead.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataRead[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataRead[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataRead[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
conn.Close();
conn.Open();
string sqla = "Update attendance_tbl SET TimeOut = '" + Time + "' , Name ='" + dataGridView1.Rows[i].Cells["Column3"].Value + "' where stud_id = '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
cmd = new MySqlCommand(sqla, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column7"].Value = DateTime.Now.ToLongTimeString();
This is My Insert Code:
//IF Not In Execute Time-In/Not exist in tbl attendance
string sqlQu = "select ID,Name,Course,Image from tbl_student_list where ID= '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
md = new MySqlCommand(sqlQu, conn);
MySqlDataReader DataReaders = cmd.ExecuteReader();
DataReaders.Read();
if (DataReaders.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataReaders[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataReaders[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataReaders[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
Purpose f2 = new Purpose();
if (f2.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows[i].Cells["Column5"].Value = f2.Rad;
}
conn.Close();
conn.Open();
string sql = "insert into attendance_tbl(stud_id,Date,Name,Course,Purpose,TimeIn)values('" + dataGridView1.Rows[i].Cells["Column1"].Value + "','" + Date + "','" + dataGridView1.Rows[i].Cells["Column3"].Value + "','" + dataGridView1.Rows[i].Cells["Column4"].Value + "','" + dataGridView1.Rows[i].Cells["Column5"].Value + "','" + Time + "')";
cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column6"].Value = DateTime.Now.ToLongTimeString();

createNativeQuery - return Page

I have the following custom implementation of my repository.
public final EntityManager entityManager;
public ImputacionRepositoryImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public List<ImputacionData> imputacionesList() {
Query q = entityManager.createNativeQuery("SELECT " + "empleado.id as empleadoId,"
+ "MAX(imputacion.dia) as dia," + "imputacion.id as id " + "FROM rrhh.empleado empleado "
+ "JOIN rrhh.imputacion imputacion ON imputacion.empleado = empleado.id "
+ "WHERE empleado.id NOT IN (SELECT empleado.id " + "FROM rrhh.empleado empleado "
+ "LEFT JOIN rrhh.imputacion imputacion ON imputacion.empleado = empleado.id " + "WHERE "
+ "(imputacion.dia >= '2017-06-01' AND imputacion.dia <= '2017-10-31') "
+ "GROUP BY empleado.id,imputacion.empleado, imputacion.id) " + "AND true=true "
+ "GROUP BY empleado.id,imputacion.empleado, imputacion.id ORDER BY imputacion.dia DESC");
List<ImputacionData> imputaciones = q.getResultList();
return imputaciones;
}
And I need that instead of returning a List<ImputacionData>, return Page<ImputacionData>, but I do not know if it is possible, and how to do it.
So you can use page implementation in Spring, in Your case it's may look like:
#Override
public Page<ImputacionData> imputacionesList() {
Query q = entityManager.createNativeQuery("SELECT " + "empleado.id as empleadoId,"
+ "MAX(imputacion.dia) as dia," + "imputacion.id as id " + "FROM rrhh.empleado empleado "
+ "JOIN rrhh.imputacion imputacion ON imputacion.empleado = empleado.id "
+ "WHERE empleado.id NOT IN (SELECT empleado.id " + "FROM rrhh.empleado empleado "
+ "LEFT JOIN rrhh.imputacion imputacion ON imputacion.empleado = empleado.id " + "WHERE "
+ "(imputacion.dia >= '2017-06-01' AND imputacion.dia <= '2017-10-31') "
+ "GROUP BY empleado.id,imputacion.empleado, imputacion.id) " + "AND true=true "
+ "GROUP BY empleado.id,imputacion.empleado, imputacion.id ORDER BY imputacion.dia DESC");
Page<ImputacionData> page = new PageImpl<>(q.getResultList());
return page;
}

azure REST API communication

I'm currently trying retrieve list share available in my Azure account from salesforce. I'm trying to implement the example from below sample code:
https://learn.microsoft.com/en-us/rest/api/storageservices/list-shares#samplerequestandresponse
//private key: access key of my account
string storageKey =private key;
string storageName = 'accountName';
Datetime dt = Datetime.now();
string formattedDate = dt.formatGMT('EEE, dd MMM yyyy HH:mm:ss')+ ' GMT';
system.debug('formattedDate--'+formattedDate);
string CanonicalizedHeaders = 'x-ms-date:'+formattedDate+'\nx-ms-version:2016-05-31';
string CanonicalizedResource = '/' + storageName + '/\ncomp:list';
string StringToSign = 'GET\n\n\n\n\n\n\n\n\n\n\n\n' + CanonicalizedHeaders+'\n'+CanonicalizedResource;
system.debug('StringToSign--'+StringToSign);
Blob temp = EncodingUtil.base64Decode(storageKey);
Blob hmac = Crypto.generateMac('HmacSHA256',Blob.valueOf(StringToSign),temp ); //StringToSign
system.debug('oo-'+EncodingUtil.base64Encode(hmac));
HttpRequest req = new HttpRequest();
req.setMethod('GET');
//req.setHeader('content-type', 'application/xml');
req.setHeader('x-ms-version','2016-05-31' );
req.setHeader('x-ms-date', formattedDate);
string signature = EncodingUtil.base64Encode(hmac);
string authHeader = 'SharedKey salesforcestrongaccount'+':'+signature;
req.setHeader('Authorization',authHeader);
req.setEndpoint('https://<accountName>.file.core.windows.net/?comp=list');
Http http = new Http();
HTTPResponse res;
res = http.send(req);
System.debug(LoggingLevel.INFO, 'http.send result status: ' + res.getStatus());
Any help?
As Gaurav Mantri says, there are something wrong with your stringToSign. So you will get this error.
The right Shared Key Authentication is like this:
StringToSign = VERB + "\n" +
Content-Encoding + "\n" +
Content-Language + "\n" +
Content-Length + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
If-Modified-Since + "\n" +
If-Match + "\n" +
If-None-Match + "\n" +
If-Unmodified-Since + "\n" +
Range + "\n" +
CanonicalizedHeaders +
CanonicalizedResource;
Here I create a test demo, you could refer to it.
List share:
string storageAccount = "storage account";
string accessKey = "accountkey";
string resourcePath = "?comp=list";
string uri = #"https://" + storageAccount + ".file.core.windows.net/" + resourcePath;
// Web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
request.Headers["x-ms-version"] = "2015-02-21";
String stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + request.Headers["x-ms-date"] + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + storageAccount + "/" + "\ncomp:list"; // resources
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
string strAuthorization = "SharedKey " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));
request.Headers["Authorization"] = strAuthorization;
Task<WebResponse> response = request.GetResponseAsync();
HttpWebResponse responseresult = (HttpWebResponse)response.Result;
using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
{
string jsonData = r.ReadToEnd();
Console.WriteLine(jsonData);
}
Result:
Java:
private static final String account = "accountname";
private static final String key = "Key";
public static void main(String args[]) throws Exception {
// String urlString = "http://" + account + ".file.core.windows.net/sampleshare/name.txt";
String urlString = "https://" + account + ".file.core.windows.net/?comp=list";
HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
getFileRequest(connection, account, key);
connection.connect();
System.out.println("Response message : " + connection.getResponseMessage());
System.out.println("Response code : " + connection.getResponseCode());
BufferedReader br = null;
if (connection.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
public static void getFileRequest(HttpURLConnection request, String account, String key) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
String stringToSign = "GET\n" + "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + date + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + account + request.getURL().getPath() + "\ncomp:list"; // resources
System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
request.setRequestMethod("GET");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2015-02-21");
request.setRequestProperty("Authorization", auth);
}
private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
String auth = "SharedKey " + account + ":" + authKey;
return auth;
}

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

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.