Generic Method to Create Multiple Fragments - java

I want to write a method that creates multiple fragments for me and I am not sure how to do this. After a few attempts I got more confused.
Here is how I typically and creating two fragments
private void createFragDog(Animals animals) {
DogFragment frag = DogFragment.newInstance(ArrayList<Dogs> animals.getDogs());
...
*frag.(do fragment manager stuff and commit())*
...
}
Second call to create fragment
private void createFragCat(Animals animals) {
CatFragment frag = CatFragment.newInstance(ArrayList<Cats> animals.getCats());
...
*frag.(do fragment manager stuff and commit())*
...
}
Being that the newInstance method is static I can't seem to figure out how to make a generic method and just pass in the class types. Also the object passed into newInstance is not always an array. Here is my attempt:
private <T,E> void animalFragments(Class<T> frag, Class<E> animalType, Object obj){
if (obj == null) return;
if (obj instanceof List<?>) {
if (((List<E>)obj).isEmpty()) return;
}
try {
T fragment = (T) frag.newInstance();
?? Not sure what to do now or how to call up method that is static but specific to both.
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

Did it this way hope this helps.
private <T,E> void animalFragments(Class<T> frag, Object obj){
Method m = null;
try {
m = frag.newInstance().getClass().getDeclaredMethod("newInstance", obj.getClass());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (m != null) {
T fragment = null;
try {
fragment = (T) m.invoke(null, obj);
if (fragment != null) {
FragmentTransaction trans = this.getSupportFragmentManager().beginTransaction();
trans.add(R.id.ll_fragments_container, (Fragment) fragment, fragment.getClass().getSimpleName());
trans.commit();
return true;
}
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

Related

Using Glide inside a Runnable that is placed outside onViewCreated()

I am using Glide function to load an image form a server response. The code below is working properly inside an onViewCreated function, but i want to make a Handler to verify the internet connection and I am declaring the Runnable as a global variable. Well inside that Runnable I can't use getActivity as a context/container. What should I use?
Here is the code inside onViewCreated():
try {
Glide.with(this.getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
And here is the Runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
if(!isNetworkConnected())
{
handler.postDelayed(runnable , time);
}
else
{
try {
jsonObject = new JSONObject(MainActivity.dispensaries);
jsonArray = jsonObject.optJSONArray("dispensaries");
Log.e(TAG, "jsonArray = " + jsonArray);
jsonObject = null;
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
if(MainActivity.ID.equals(object.get("dispensary_id")))
{
jsonObject = object;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
Glide.with(this.).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Try this, basically, you needed runOnUiThread of activity class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Glide.with(getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
});

Update an object in RecyclerView

I have a problem with updating an item in RecycleView.
When i try to edit a dream object and save it then it gets updated in database but not in the list of dream and I don't know why.
This method creates and updates a dream object.
#OnClick({R.id.addTagDream, R.id.saveDreamButton})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.addTagDream:
Intent intent = new Intent(AddEditDreamActivity.this, SelectDreamActivity.class);
startActivityForResult(intent, SELECTED_DREAM);
break;
case R.id.saveDreamButton:
boolean hasError = false;
...
if (!hasError) {
// check if exit dream about id
try {
myDreamList = myDreamDao.queryForEq(MyDream.Columns.MY_DREAM_ID, dreamId);
} catch (SQLException e) {
e.printStackTrace();
}
chcek if dream exist
if (myDreamList != null && !myDreamList.isEmpty()) {
// update dream
UpdateBuilder<MyDream, ?> updateMyDream = myDreamDao.updateBuilder();
// condition update dream about dream id
try {
updateMyDream.where().eq(MyDream.Columns.MY_DREAM_ID, dreamId);
} catch (SQLException e) {
e.printStackTrace();
}
// update column title dream
try {
updateMyDream.updateColumnValue(MyDream.Columns.TITLE_DREAM, dreamTitle);
} catch (SQLException e) {
e.printStackTrace();
}
// update dream description
try {
updateMyDream.updateColumnValue(MyDream.Columns.DESCRIPTION, dreamDescription);
} catch (SQLException e) {
e.printStackTrace();
}
// update dream symbol
try {
updateMyDream.updateColumnValue(MyDream.Columns.SYMBOL_DREAM, selectSymbolDream);
} catch (SQLException e) {
e.printStackTrace();
}
try {
updateMyDream.update();
} catch (SQLException e) {
e.printStackTrace();
}
finish();
}
}
break;
}
}
Use adapter.notifyDataSetChanged() or notifyItemInserted() whenever you are adding values in list
Hope this will help you

save server response in sqlite database(offline)

i call below php webservice and get xml response and parse resonse and set it to hashmap.now i want save server response in offline mode .can i save data in offline mode.how plz give me answer.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(Constant.TAG_CODE, response));
if (code == 1) {
spinner.clear();
ArrayList<String> eventlist = XMLManualParser.getMultipleTagList(Constant.TAG_LIST, response);
for (int i = 0; i < eventlist.size(); ++i) {
String responseContent = eventlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
String title = XMLManualParser.getTagValue(Constant.title, responseContent);
hashMap.put("title", title);
hashMap.put("id", XMLManualParser.getTagValue(Constant.id, responseContent));
hashMap.put("url", XMLManualParser.getTagValue(Constant.url, responseContent));
hashMap.put("balanceurl", XMLManualParser.getTagValue(Constant.balanceurl, responseContent));
spinner.add(hashMap);
}
} else {
Toast.makeText(SettingsEditActivity.this, "no data found", Toast.LENGTH_SHORT).show();
}
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(SettingsEditActivity.this, spinner);
settingsBinding.splist.setAdapter(customSpinnerAdapter);
settingsBinding.splist.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Android Custom Spinner Example Output..." + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can save your response into a file and get in offline
public static void saveDataSingleItemDetails(Context context,String file, MainListModel data) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(file, MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
return;
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MainListModel getSinglItemDetails(Context context,String file) {
MainListModel items = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = context.openFileInput(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return items;
} catch (NullPointerException e) {
return items;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return items;
}
try {
items = (MainListModel) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}

Clear apps cache in android

I am implementing an app to clean cache of installed applications,And what I have tried is following :
public static void freeAllAppsCache(final Handler handler,Context oContext)
{
File externalDir = oContext.getApplicationContext().getExternalCacheDir();
if (externalDir == null) {
return;
}
PackageManager pm = oContext.getApplicationContext().getPackageManager();
List<ApplicationInfo> installedPackages = pm.getInstalledApplications(PackageManager.GET_GIDS);
for (ApplicationInfo info : installedPackages)
{
String externalCacheDir = externalDir.getAbsolutePath().replace(oContext.getApplicationContext().getPackageName(), info.packageName);
File externalCache = new File(externalCacheDir);
if (externalCache.exists() && externalCache.isDirectory())
{
deleteFile(externalCache);
}
}
try {
Method freeStorageAndNotify = pm.getClass()
.getMethod("freeStorageAndNotify", long.class, IPackageDataObserver.class);
long freeStorageSize = Long.MAX_VALUE;
freeStorageAndNotify.invoke(pm, freeStorageSize, new IPackageDataObserver.Stub() {
#Override
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
Message msg = handler.obtainMessage(MainActivity.MSG_SYS_CACHE_CLEAN_FINISH);
msg.sendToTarget();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static boolean deleteFile(File file) {
if (file !=null && file.isDirectory()) {
String[] children = file.list();
if (children != null)
{
for (String name : children) {
boolean suc = deleteFile(new File(file, name));
if (!suc) {
return false;
}
}
}
}
return file.delete();
}
And I also have declared following permissions in manifest file :
uses-permission android:name="android.permission.GET_PACKAGE_SIZE"
uses-permission android:name="android.permission.CLEAR_APP_CACHE"
But it's not clearing cache. What's the reason ?

How to get current top activity context

In my static method(Parameter is only one string), I want to use Dialog(new AlertDialog.Builder(mContext)), but dialog needs an activity context to construct. If I do not pass through the external context parameters, only by reflection or other methods, how to get an object of current top activity?
public static Activity getActivity() {
Class activityThreadClass = null;
try {
activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
I used this code, but when I call this method in non-Activity class, the activities is null.
Is there any other way? Can not use dialog, as long as it is able to pop up the information can be seen by the user. A point limit: does not get context from the parameter.
Use Application.ActivityLifecycleCallbacks
Implementation example:
class ActivityLifeCycleCallbackImpl implements Application.ActivityLifecycleCallbacks {
private Set<Activity> set = new HashSet<>();
#Override
public void onActivityStarted(Activity activity) {
set.add(activity);
}
#Override
public void onActivityStopped(Activity activity) {
set.remove(activity);
}
Activity getCurrentActivity() {
if (set.isEmpty()) {
return null;
}
return set.iterator().next();
}
}
and in your custom application class:
ActivityLifeCycleCallbackImpl activityLifeCycleCallback = new ActivityLifeCycleCallbackImpl();
#Override
public void onCreate() {
registerActivityLifecycleCallbacks(activityLifeCycleCallback);
}

Categories