Created
August 16, 2018 12:18
-
-
Save dineshmm23/bf671bbb1ccf293e33d87f2258c59ccd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SomeCode extends AppCompatActivity { | |
private final static long intervalTime = 3000; | |
static ArrayList<String> result = new ArrayList<String>(); | |
/** | |
* The {@link android.support.v4.view.PagerAdapter} that will provide | |
* fragments for each of the sections. We use a | |
* {@link FragmentPagerAdapter} derivative, which will keep every | |
* loaded fragment in memory. If this becomes too memory intensive, it | |
* may be best to switch to a | |
* {@link android.support.v4.app.FragmentStatePagerAdapter}. | |
*/ | |
private static String TAG = "FP_" + SomeCode.class.getSimpleName(); | |
private static String fileCount; | |
private static ArrayList<String> imageResult = new ArrayList<>(); | |
private static ArrayList<SurveyAnsVersionModel> imageResultList = new ArrayList<>(); | |
/** | |
* The {@link ViewPager} that will host the section contents. | |
*/ | |
private ViewPager mViewPager; | |
private TabLayout tabLayout; | |
private LogisticTaskTabs context; | |
private String customFieldData; | |
private String userEmail; | |
private JSONObject custom_columns; | |
private String userID; | |
private Handler handler; | |
private Runnable updateDataCount; | |
private String dirPath; | |
private Menu menu; | |
private ApiService apiService; | |
private CompositeDisposable disposable; | |
private static String getFilesCount(String dirPath, int numberOfFiles) { | |
File dir = new File(dirPath); | |
if (dir.exists()) { | |
if (dir.listFiles() == null) { | |
numberOfFiles = 0; | |
return String.valueOf(numberOfFiles); | |
} //it never execute this line even though its null | |
else { | |
File childfile[] = dir.listFiles(); | |
Log.i("file no is ", Integer.toString(childfile.length)); | |
if (childfile.length == 0) { | |
numberOfFiles = 0; | |
return String.valueOf(numberOfFiles); | |
} else { | |
numberOfFiles = childfile.length; | |
return String.valueOf(numberOfFiles); | |
} | |
} | |
} else { | |
Log.e(TAG, "getFilesCount: Directory doesn't exits", new IOException()); | |
numberOfFiles = 0; | |
return String.valueOf(numberOfFiles); | |
} | |
} | |
private static void getFilesContent(String dirPath) throws FileNotFoundException, JSONException { | |
File dir = new File(dirPath); | |
result.clear(); | |
imageResultList.clear(); | |
if (dir.exists()) { | |
if (dir.listFiles() == null) { | |
result.clear(); | |
} //it never execute this line even though its null | |
else { | |
File childfile[] = dir.listFiles(); | |
//Log.i("file no is ", Integer.toString(childfile.length)); | |
if (childfile.length == 0) { | |
result.clear(); | |
} else { | |
for (File aChildfile : childfile) { | |
String fileOutput = new Scanner(aChildfile).useDelimiter("\\A").next(); | |
JSONObject dataObj = new JSONObject(fileOutput); | |
JSONArray dataArr = dataObj.getJSONArray("data"); | |
SurveyAnsVersionModel model = new Gson().fromJson(dataObj.toString(), SurveyAnsVersionModel.class); | |
for (int i = 0; i < dataArr.length(); i++) { | |
JSONObject ansObj = dataArr.getJSONObject(i); | |
String type = ansObj.getString("type"); | |
String imagePath = ansObj.getString("answer"); | |
if (type.equalsIgnoreCase("image") && !TextUtils.isEmpty(imagePath)) { | |
File file = new File(imagePath); | |
if (file.exists()) { | |
model.setImageFile(file); | |
} | |
} | |
} | |
imageResultList.add(model); | |
result.add(fileOutput); | |
} | |
} | |
} | |
} else { | |
Log.e(TAG, "getFilesCount: Directory doesn't exits", new IOException()); | |
} | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_logistic_task_tabs); | |
context = this; | |
userEmail = PrefUtils.getUserEmail(context); | |
userID = PrefUtils.getUserID(context); | |
customFieldData = PrefUtils.getCustomFieldData(context); | |
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); | |
// Set up the ViewPager with the sections adapter. | |
mViewPager = (ViewPager) findViewById(R.id.viewPager); | |
// Create the adapter that will return a fragment for each of the three | |
// primary sections of the activity. | |
setupViewPager(mViewPager); | |
tabLayout = (TabLayout) findViewById(R.id.tabs); | |
tabLayout.setupWithViewPager(mViewPager); | |
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { | |
@Override | |
public void onTabSelected(TabLayout.Tab tab) { | |
//tabLayout.setTitle(tab.getText().toString()); | |
} | |
@Override | |
public void onTabUnselected(TabLayout.Tab tab) { | |
} | |
@Override | |
public void onTabReselected(TabLayout.Tab tab) { | |
} | |
}); | |
dirPath = context.getExternalFilesDir(null) + "/Answers/u" + userID + "/"; | |
handler = new Handler(); | |
updatingFileCountEverySec(); | |
apiService = ApiClient.getClient(context).create(ApiService.class); | |
} | |
private void updatingFileCountEverySec() { | |
updateDataCount = new Runnable() { | |
@Override | |
public void run() { | |
try { | |
fileCount = getFilesCount(dirPath, 0); | |
MenuItem item = menu.findItem(R.id.action_data_sync); | |
//String dirPath=context.getExternalFilesDir(null) + "/Answers/" + userID +"/"; | |
//String count=getFilesCount(dirPath,0); | |
LayerDrawable icon = (LayerDrawable) item.getIcon(); | |
setBadgeCount(context, icon, fileCount); | |
invalidateOptionsMenu(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
//Do something after 20 seconds | |
handler.postDelayed(updateDataCount, intervalTime); | |
} | |
}; | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
// Inflate the menu; this adds items to the action bar if it is present. | |
getMenuInflater().inflate(R.menu.menu_logistic_task_tabs, menu); | |
this.menu = menu; | |
MenuItem item = menu.findItem(R.id.action_data_sync); | |
if (!Data.workOrderType.equalsIgnoreCase(Data.SURVEY)) | |
item.setVisible(false); | |
//String dirPath=context.getExternalFilesDir(null) + "/Answers/" + userID +"/"; | |
//String count=getFilesCount(dirPath,0); | |
LayerDrawable icon = (LayerDrawable) item.getIcon(); | |
setBadgeCount(this, icon, fileCount); | |
return true; | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
// Handle action bar item clicks here. The action bar will | |
// automatically handle clicks on the Home/Up button, so long | |
// as you specify a parent activity in AndroidManifest.xml. | |
int id = item.getItemId(); | |
//noinspection SimplifiableIfStatement | |
if (id == R.id.action_data_sync) { | |
try { | |
getFilesContent(dirPath); | |
} catch (FileNotFoundException | JSONException e) { | |
e.printStackTrace(); | |
} | |
if (result != null && result.size() > 0) { | |
uploadImage(); | |
// for (int i = 0; i < result.size(); i++) { | |
// String contents = result.get(i); | |
// | |
// } | |
} | |
return true; | |
} | |
return super.onOptionsItemSelected(item); | |
} | |
private void setupViewPager(ViewPager viewPager) { | |
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); | |
. | |
. | |
. | |
viewPager.setAdapter(adapter); | |
} | |
@Override | |
protected void onResume() { | |
super.onResume(); | |
handler.postDelayed(updateDataCount, intervalTime); | |
} | |
@Override | |
protected void onPause() { | |
super.onPause(); | |
handler.removeCallbacks(updateDataCount); | |
} | |
private JSONObject buildQuestAndAnsJson2(SurveyAnsVersionModel sAVModel) { | |
JSONObject object = null; | |
try { | |
object = new JSONObject(); | |
int userId = Integer.parseInt(PrefUtils.getUserID(context)); | |
object.put("company_code", sAVModel.getCompanyCode()); | |
object.put("type", "submitSurvey"); | |
object.put("versionid", sAVModel.getVersionid()); | |
object.put("resubmit", sAVModel.getResubmit()); | |
JSONArray versionArr = new JSONArray(); | |
for (SurveyOfflineAnswerModel offlineAnsModel : sAVModel.getAnswers()) { | |
JSONObject questObj = new JSONObject(); | |
questObj.put("slno", offlineAnsModel.getSlno()); | |
questObj.put("question", offlineAnsModel.getQid()); | |
questObj.put("type", offlineAnsModel.getType()); | |
questObj.put("qid", offlineAnsModel.getQid()); | |
questObj.put("optionId", offlineAnsModel.getOptionId()); | |
questObj.put("answer", offlineAnsModel.getAnswer()); | |
questObj.put("skipped", offlineAnsModel.getSkipped()); | |
versionArr.put(questObj); | |
} | |
//Log.d(TAG, "onBtnNextClicked: FinalFrom -> \n" + versionArr); | |
object.put("data", versionArr); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
return object; | |
} | |
private ObservableSource<ResponseBody> getSubmitResponse(JSONObject datajson) { | |
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), (datajson.toString())); | |
return apiService.submitSurvey2(body); | |
} | |
void resetData(String imageURL, SurveyAnsVersionModel ansVersionModel) { | |
int quesOrderNo = -1; | |
Pattern pattern = Pattern.compile("_Q(.*?)_"); | |
Matcher matcher = pattern.matcher(imageURL); | |
if (matcher.find()) { | |
quesOrderNo = Integer.parseInt(matcher.group(1)); | |
} | |
if (quesOrderNo != -1) { | |
File file = ansVersionModel.getImageFile(); | |
if (file.exists()) { | |
boolean isFileDeleted = file.delete(); | |
Log.d(TAG, "resetData() isFileDeleted: " + isFileDeleted); | |
} | |
for (SurveyOfflineAnswerModel offlineAnswerModel : | |
ansVersionModel.getAnswers()) { | |
if (offlineAnswerModel.getQid().equals(quesOrderNo)) { | |
offlineAnswerModel.setAnswer(imageURL); | |
} | |
} | |
} | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
} | |
void uploadImage() { | |
for (int i = 0; i < imageResultList.size(); i++) { | |
SurveyAnsVersionModel ansVersionModel = imageResultList.get(i); | |
Observable<ResponseBody> getuploadMultiFile2 = apiService.uploadMultiFile2(buildImageReqJSon(ansVersionModel)); | |
getuploadMultiFile2 | |
.concatMap(new Function<ResponseBody, ObservableSource<ResponseBody>>() { | |
@Override | |
public ObservableSource<ResponseBody> apply(ResponseBody responseBody) throws Exception { | |
String res1 = responseBody.string(); | |
JSONObject resObj = new JSONObject(res1); | |
if (resObj.optBoolean("success")) { | |
resetData(resObj.getString("imageURL"), ansVersionModel); | |
} else { | |
throw new RuntimeException("Unable to upload image"); // this will be thorwn to onError | |
} | |
JSONObject obj = buildQuestAndAnsJson2(ansVersionModel); | |
return getSubmitResponse(obj); | |
} | |
}).map(new Function<ResponseBody, String>() { | |
@Override | |
public String apply(ResponseBody responseBody) throws Exception { | |
String res = responseBody.string(); | |
Log.d(TAG, "apply() returned: " + res); | |
return res; | |
} | |
}) | |
.subscribeOn(Schedulers.newThread()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(new Observer<String>() { | |
@Override | |
public void onSubscribe(Disposable d) { | |
Log.d(TAG, " onSubscribe : " + d.isDisposed()); | |
} | |
@Override | |
public void onNext(String s) { | |
Log.d(TAG, "onNext() returned: " + s); | |
try { | |
JSONObject sObj = new JSONObject(s); | |
boolean isSuccess = sObj.getBoolean("success"); | |
if (isSuccess) { | |
int uid = sObj.getInt("uid"); | |
int versionid = sObj.getInt("versionid"); | |
int woid = sObj.getInt("woid"); | |
int cid = sObj.getInt("cid"); | |
deletefile(uid, versionid, woid, cid); | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
@Override | |
public void onError(Throwable e) { | |
e.printStackTrace(); | |
} | |
@Override | |
public void onComplete() { | |
Log.d(TAG, " onComplete"); | |
} | |
}); | |
} | |
} | |
private MultipartBody buildImageReqJSon2(ArrayList<SurveyAnsVersionModel> versionModels) { | |
MultipartBody requestBody = null; | |
for (int i = 0; i < versionModels.size(); i++) { | |
SurveyAnsVersionModel ansVersionModel = versionModels.get(i); | |
try { | |
MultipartBody.Builder builder = new MultipartBody.Builder(); | |
builder.setType(MultipartBody.FORM); | |
JSONObject formObj = new JSONObject(); | |
File file = ansVersionModel.getImageFile(); | |
builder.addFormDataPart("filename[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); | |
formObj.put("description", ansVersionModel.getdesc()); | |
builder.addFormDataPart("data", formObj.toString()); | |
requestBody = builder.build(); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
return requestBody; | |
} | |
private MultipartBody buildImageReqJSon(SurveyAnsVersionModel ansVersionModel) { | |
MultipartBody requestBody = null; | |
try { | |
MultipartBody.Builder builder = new MultipartBody.Builder(); | |
builder.setType(MultipartBody.FORM); | |
JSONObject formObj = new JSONObject(); | |
File file = ansVersionModel.getImageFile(); | |
builder.addFormDataPart("filename[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); | |
//formObj.put("qid", questionModel.getId()); | |
// builder.addFormDataPart("qid", String.valueOf(questionModel.getId())); | |
// builder.addFormDataPart("slno", String.valueOf(questionModel.getQuesOrderNo())); | |
formObj.put("versionid", ansVersionModel.getVersionid()); | |
formObj.put("company_code", ansVersionModel.getCompanyCode()); | |
formObj.put("woid", ansVersionModel.getWoid()); | |
builder.addFormDataPart("data", formObj.toString()); | |
requestBody = builder.build(); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
return requestBody; | |
} | |
void deletefile(int uid, int vid, int woid, int cid) { | |
String dirPath = context.getExternalFilesDir(null) + "/Answers/u" + uid + "/"; | |
final File folder = new File(dirPath); | |
String filename = "survey_v" + vid + "_c" + cid + "_w" + woid + ".json"; | |
final File[] files = folder.listFiles(new FilenameFilter() { | |
@Override | |
public boolean accept(final File dir, | |
final String name) { | |
return name.matches(filename); | |
} | |
}); | |
for (final File file : files) { | |
if (!file.delete()) { | |
Log.d(TAG, "deletefile() returned: Can't remove" + file.getAbsolutePath()); | |
} | |
} | |
} | |
/** | |
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to | |
* one of the sections/tabs/pages. | |
*/ | |
class ViewPagerAdapter extends FragmentPagerAdapter { | |
private final List<Fragment> mFragmentList = new ArrayList<>(); | |
private final List<String> mFragmentTitleList = new ArrayList<>(); | |
public ViewPagerAdapter(FragmentManager manager) { | |
super(manager); | |
} | |
@Override | |
public Fragment getItem(int position) { | |
return mFragmentList.get(position); | |
} | |
@Override | |
public int getCount() { | |
return mFragmentList.size(); | |
} | |
public void addFragment(Fragment fragment, String title) { | |
mFragmentList.add(fragment); | |
mFragmentTitleList.add(title); | |
} | |
@Override | |
public CharSequence getPageTitle(int position) { | |
return mFragmentTitleList.get(position); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment