Bundle/getArguments() gives NullPtrException - java

I want to pass an ArrayList to my fragment from my activity that is accessed through the bottom navigation bar, the bundle returns null when I call getInt() or getParcelableArrayList()
EDIT: pasted whole files, in hope that will help... + put the bundle in on create(didn't help)
Code:
main activity(where it's sent)
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private AdView mAdView;
private boolean isAdsRemoved;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private List<AppListModel> list = new ArrayList<>();
private int totalUsage = 0;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkForPermission(this)) {
startActivity(new Intent(this, CheckForPermissionActivity.class));
finish();
}
long startTime = System.currentTimeMillis() - 86400000;
long endTime = System.currentTimeMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService("usagestats");
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
for (UsageStats us : queryUsageStats) {
Drawable icon;
int totalTimeMin = (int) us.getTotalTimeInForeground() / 60000;
boolean alreadyThere = false;
PackageManager pm = getPackageManager();
ApplicationInfo ai;
if (us.getPackageName().equals("com.android.systemui")) {
continue;
}
try {
ai = pm.getApplicationInfo(us.getPackageName(), 0);
icon = getPackageManager().getApplicationIcon(us.getPackageName());
} catch (PackageManager.NameNotFoundException e) {
ai = null;
icon = null;
Log.d(TAG, "Package name not found");
e.printStackTrace();
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
if (applicationName.length() > 15) {
applicationName = applicationName.substring(0, Math.min(applicationName.length(), 13)) + "...";
}
//if packages that have the same names, but are registered multiple times, they are merged
if (list.size() > 0) {
for (AppListModel item : list) {
if (item.getAppName().equals(applicationName)) {
item.setTotalTime(totalTimeMin + item.getTotalTime());
totalUsage += totalTimeMin;
alreadyThere = true;
}
}
}
if (totalTimeMin > 0 && !alreadyThere) {
if (!applicationName.equals("(unknown)")) {
list.add(new AppListModel(applicationName, icon, totalTimeMin));
}
Log.d(TAG, us.getPackageName() + " = " + us.getTotalTimeInForeground());
totalUsage += totalTimeMin;
}
}
preferences = getSharedPreferences("label", 0);
if (preferences.getBoolean("ad_removed", false)) {
isAdsRemoved = true;
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (preferences.getBoolean("ad_removed", false)) {
mAdView.setVisibility(View.GONE);
}
if (!preferences.getBoolean("ad_removed", false) && !isAdsRemoved) {
Intent intent = getIntent();
isAdsRemoved = intent.getBooleanExtra("ad_removal", false);
}
editor = preferences.edit();
editor.putBoolean("ad_removed", isAdsRemoved).commit();
bottomNavigationView = findViewById(R.id.bottomNavigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
bottomNavigationView.setSelectedItemId(R.id.itemDashboard);
Fragment dashboard = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
dashboard.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, dashboard).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.itemStats:
selectedFragment = new FragmentStats();
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
case R.id.itemStore:
selectedFragment = new FragmentStore();
break;
case R.id.itemSettings:
selectedFragment = new FragmentSettings();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
private boolean checkForPermission(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
FragmentDashboard
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//View itself
view = inflater.inflate(R.layout.fragment_dashboard, container, false);
//'TIME WASTED' counter
count = view.findViewById(R.id.mainFragmentText);
//RecyclerView
recyclerView = view.findViewById(R.id.recyclerView);
//Buttons
showAllBtn = view.findViewById(R.id.showAllButton);
hideBtn = view.findViewById(R.id.hideAllButton);
timeNotifBtn = view.findViewById(R.id.timeButton);
stopLimiterButton = view.findViewById(R.id.disableLimit);
list = getArguments().getParcelableArrayList("arrayList");
totalUsage = getArguments().getInt("totalUsage", 0);
int totalUsageHrs = (int) totalUsage / 60;
int totalUsageMin = (int) totalUsage - totalUsageHrs * 60;
if (totalUsageHrs == 0) {
count.setText(totalUsageMin + " minutes");
} else {
count.setText(totalUsageHrs + " hours, " + totalUsageMin + " minutes");
}
//sorts list in descending order
Collections.sort(list, new Comparator<AppListModel>() {
#Override
public int compare(AppListModel appListModel, AppListModel t1) {
return Integer.valueOf(t1.getTotalTime()).compareTo(Integer.valueOf(appListModel.getTotalTime()));
}
});
mostUsedApps = list.subList(0, Math.min(list.size(), 3));
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.INVISIBLE);
hideBtn.setVisibility(View.VISIBLE);
}
});
hideBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hideBtn.setVisibility(View.GONE);
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.VISIBLE);
hideBtn.setVisibility(View.INVISIBLE);
}
});
timeNotifBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (totalUsage > 720) {
Toast.makeText(getActivity(), "Take a break, you have spent too much on your phone", Toast.LENGTH_SHORT).show();
} else {
DialogDashboard dialogDashboard = new DialogDashboard();
dialogDashboard.show(getChildFragmentManager(), "notif_dialog");
}
}
});
stopLimiterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isJobServiceOn(getActivity())) {
JobScheduler scheduler = (JobScheduler) getActivity().getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.cancel(JOB_ID);
} else {
Toast.makeText(getActivity(), "No limit set", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
at com.example.dashboard.FragmentDashboard.onCreateView(FragmentDashboard.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1395)
at android.app.Activity.performStart(Activity.java:7348)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3145)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7078)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
EDIT 2, I fixed the problem, I just put the bundle in both onCreate and onMenuItemSelected

case R.id.itemStats:
selectedFragment = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
selectedFragment.setArguments(bundle);
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
In this part of your code you instantiate FragmentDashboard in two case statement which in second one you did not pass any bundle as arguments and because this you get error when you call getArguments().get... in it.

You only set the arguments on your FragmentStats instance. Other fragments such as the FragmentDashboard seen in the stacktrace don't have arguments set, and getArguments() returns null.
If you want the same arguments to be applied to all fragments, move the Bundle setup and setArguments() after the switch-case. (And maybe add a default case too so selectedFragment won't ever be null.)

Related

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

Check if a property of a custom object ArrayList is an empty string or not?

I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.

below calculation work in API?

i created checkoutpage then it contain total,payment due and payment balance. If give total it show the payment due amount & payment balance amount in mobile app. But it doesn't update the browser?
public class FinalCheckOutActivity extends Activity implements View.OnClickListener {
private AQuery mAQuery;
private TransparentProgressDialog mTransparentProgressDialog;
private String mStrCheckOut = "", mStrGEtData = "", mStrAddressData = "", mStrPaypAl = "";
private Spinner mSpnDefualtAddress, mSpnShipAddress;
private Button mBtnPlaceOrder;
private CheckBox mChBxSameAddres, mChkBxDiffAddress, mChkBoxAccept;
private RadioButton mRdoPayPal, mRdoCash;
private RadioGroup mRdoGroupPay;
private ImageView mIvBack;
private TextView mTvAddAddress, mTvSubTot, mTvDiscount, mTVGrandTot, mTvPendingAmt, mTvPayNow, mIvAddAddress;
private ArrayList<SpinnerData> mArrayListAddres;
private LinearLayout mLinearLayoutShiipingMethod, mLinearLayoutPayMethod, mLinearLayoutOrderDetails;
private RadioGroup mRbnOptionshippingmethods;
private ArrayList<UserAddressData> mArrayListshippingMethod;
private ArrayList<UserAddressData> mArrayListPaymentMethods;
private String shippingMethodId;
private RadioGroup mRbnOptionPaymentMethods;
private String shippingPaymentID;
private View viewOrderData;
private JSONObject mJsonObject, jsonObjectData;
private LinearLayout mLinearLayoutTabShiping;
private RadioButton newRadioButton;
private ArrayList<SpinnerData> mArrayListBilign;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_check_out);
//setUI();
}
private void setUI() {
mAQuery = new AQuery(this);
mTransparentProgressDialog = new TransparentProgressDialog(this, R.drawable.ic_loader_image);
mSpnDefualtAddress = (Spinner) findViewById(R.id.spn_default_address);
mSpnShipAddress = (Spinner) findViewById(R.id.spn_ship_address);
mBtnPlaceOrder = (Button) findViewById(R.id.btn_place_order);
mRdoGroupPay = (RadioGroup) findViewById(R.id.rdo_payment);
mRdoCash = (RadioButton) findViewById(R.id.rdo_cash);
mRdoPayPal = (RadioButton) findViewById(R.id.rdo_paypal);
mLinearLayoutTabShiping = (LinearLayout) findViewById(R.id.layout_shiping);
mChBxSameAddres = (CheckBox) findViewById(R.id.chk_ship_to_same_address);
mChkBxDiffAddress = (CheckBox) findViewById(R.id.chk_diff_ship_address);
mChkBoxAccept = (CheckBox) findViewById(R.id.chk_acceept);
mLinearLayoutShiipingMethod = (LinearLayout) findViewById(R.id.layout_shipping_method);
mLinearLayoutPayMethod = (LinearLayout) findViewById(R.id.layout_payment_method);
mLinearLayoutOrderDetails = (LinearLayout) findViewById(R.id.lv_shipping_order_view);
mIvAddAddress = (TextView) findViewById(R.id.img_add_address);
mTvSubTot = (TextView) findViewById(R.id.tv_subtotal);
mTvDiscount = (TextView) findViewById(R.id.tv_discount);
mTVGrandTot = (TextView) findViewById(R.id.tv_grand_tot);
mTvPendingAmt = (TextView) findViewById(R.id.tv_pending_pay);
mTvPayNow = (TextView) findViewById(R.id.tv_payable_now);
mIvBack = (ImageView) findViewById(R.id.img_back_one_page);
mArrayListAddres = new ArrayList<>();
mArrayListshippingMethod = new ArrayList<>();
mArrayListPaymentMethods = new ArrayList<>();
mArrayListBilign = new ArrayList<>();
mBtnPlaceOrder.setOnClickListener(this);
mIvAddAddress.setOnClickListener(this);
// mTvAddAddress.setOnClickListener(this);
mIvBack.setOnClickListener(this);
ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
mChBxSameAddres.setChecked(true);
mLinearLayoutTabShiping.setVisibility(View.GONE);
mChBxSameAddres.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mLinearLayoutTabShiping.setVisibility(View.GONE);
//mSpnShipAddress.setVisibility(View.GONE);
// perform logic
}
}
});
mChkBxDiffAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mChBxSameAddres.setChecked(false);
mLinearLayoutTabShiping.setVisibility(View.VISIBLE);
}
}
});
SpinnerData data = new SpinnerData();
data.setmStrName("Select Address");
mArrayListAddres.add(data);
mSpnDefualtAddress.setAdapter(new SpinnerAdapter(this, mArrayListAddres));
getFinalCheckOutData();
}
#Override
protected void onResume() {
super.onResume();
setUI();
//getAddressData();
}
/**
* get user address web service call
**/
private void getAddressData() {
mStrAddressData = getString(R.string.WS_HOST) + getString(R.string.WS_GET_MULTIPLE_ADDRESS);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("customer_id", SessionClass.getUserId(this));
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrAddressData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* get user address web service call
**/
private void getPaypalData() {
mStrPaypAl = getString(R.string.WS_HOST) + getString(R.string.WS_PAYPAL);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("order_increment_id", orderID);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrPaypAl, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Get final checkout data
**/
private void getFinalCheckOutData() {
mStrGEtData = getString(R.string.WS_HOST) + getString(R.string.WS_FINAL_CHECKOUT_DETAIls);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrGEtData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Place order web service call
**/
private void placeOrder() {
mStrCheckOut = getString(R.string.WS_HOST) + getString(R.string.WS_PLACE_ORDER);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
hashMap.put("checkoutdetails", jsonObjectData.toString());
Log.e("Place order", "hash map-->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrCheckOut, hashMap, JSONObject.class, ajaxCallback);
} else {
//showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
private boolean checkValidationn() {
if (mSpnDefualtAddress.getSelectedItemPosition() == 0) {
showAlert("Please select billing address first.", -1);
mSpnDefualtAddress.requestFocus();
return false;
} else if (mRbnOptionshippingmethods.getCheckedRadioButtonId() == -1) {
showAlert("Please select shipping method first.", -1);
mRbnOptionshippingmethods.requestFocus();
return false;
} else if (mRdoGroupPay.getCheckedRadioButtonId() == -1) {
showAlert("Please select payment method first.", -1);
mRdoGroupPay.requestFocus();
return false;
} else if (!mChkBoxAccept.isChecked()) {
showAlert("Please select terms and conditions first.", -1);
mChkBoxAccept.requestFocus();
return false;
}
return true;
}
private void showAlert(String message, final int flg) {
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
aBuilder.setCancelable(false);
aBuilder.setMessage(message);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setNxtFlg(flg);
}
});
aBuilder.create();
aBuilder.show();
}
private void setNxtFlg(int flg) {
switch (flg) {
case 3:
Intent intent = new Intent(FinalCheckOutActivity.this, PayPalPaymentActivity.class);
intent.putExtra("key", urlMain);
intent.putExtra("order_id", orderID);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(FinalCheckOutActivity.this, MainActivity.class);
intent1.putExtra("key", "4");
startActivity(intent1);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
}
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.btn_place_order:
getCheckOutData();
if (checkValidationn()) {
placeOrder();
}
break;
case R.id.img_back_one_page:
onBackPressed();
//finish();
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
case R.id.img_add_address:
intent = new Intent(FinalCheckOutActivity.this, CheckoutActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
/*case R.id.txt_add_address:
intent = new Intent(FinalCheckOutActivity.this, AddUserAddressActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
//finish();
break;*/
}
}
private void getCheckOutData() {
mJsonObject = new JSONObject();
jsonObjectData = new JSONObject();
try {
if (mChBxSameAddres.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
} else {
// jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
}
if (mChkBxDiffAddress.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
} else {
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
}
JSONObject mJsonObjectPay = new JSONObject();
if (mRdoCash.isChecked()) {
shippingPaymentID = "checkmo";
mJsonObjectPay.put("method", shippingPaymentID);
} else if (mRdoPayPal.isChecked()) {
shippingPaymentID = "paypaladaptive";
mJsonObjectPay.put("method", shippingPaymentID);
}
jsonObjectData.put("payment", mJsonObjectPay);
jsonObjectData.put("shipping_method", shippingMethodId);
jsonObjectData.put("checkout_method", "customer");
jsonObjectData.put("onestepcheckout_feedback_freetext", "");
jsonObjectData.put("accept_terms", 1);
jsonObjectData.put("customer_id", SessionClass.getUserId(FinalCheckOutActivity.this));
mJsonObject.put("checkoutdetails", jsonObjectData);
//showAlert("place order array" + jsonObjectData.toString(), -1);
//Log.e("Place order", "Data-->" + jsonObjectData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private String orderID;
private String urlMain;
/**
* web service responce
**/
AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
super.callback(url, object, status);
Log.e("Check out", "Url-->" + url);
Log.e("Check out", "Responce-->" + object);
if (object != null) {
if (status.getCode() == 200) {
if (mTransparentProgressDialog.isShowing()) {
mTransparentProgressDialog.dismiss();
}
if (url.equalsIgnoreCase(mStrAddressData)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
setAddressData(object.getJSONArray("data"));
//getFinalCheckOutData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrGEtData)) {
try {
String now = getIntent().getExtras().getString("pay_now");
String due = getIntent().getExtras().getString("pay_due");
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
setShippingMethods(mJsonObject.getJSONArray("shippingmethods"));
setPaymentMethods(mJsonObject.getJSONArray("paymentmethods"));
if (!mJsonObject.isNull("items")) {
setOrderView(mJsonObject.getJSONArray("items"));
}
mTvSubTot.setText(mJsonObject.getString("subtotal"));
mTvDiscount.setText(mJsonObject.getString("discount"));
mTVGrandTot.setText(mJsonObject.getString("grandtotal"));
// mTvPendingAmt.setText(mJsonObject.getString("pendingpayment"));
// mTvPayNow.setText(mJsonObject.getString("payablenow"));
mTvPendingAmt.setText(now);
mTvPayNow.setText(due);
getAddressData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrCheckOut)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
//showAlert("Your order placed successfully.", -1);
if (shippingPaymentID.equalsIgnoreCase("paypaladaptive")) {
JSONObject mJsonObject = object.getJSONObject("data");
orderID = mJsonObject.getString("order_increment_id");
getPaypalData();
} else {
showAlert("Your order placed successfully.", 1);
}
//SessionClass.logout(FinalCheckOutActivity.this);
SessionClass.setUrerCartId(FinalCheckOutActivity.this, "");
} else if (object.getString("errorcode").equalsIgnoreCase("1")) {
showAlert("There is error in order creation.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrPaypAl)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
urlMain = mJsonObject.getString("url").replace("/\\/", "");
Log.e("Final url", "Url-->" + urlMain);
showAlert("Click on ok to continue.", 3);
} else if (object.getString("errorcode").equalsIgnoreCase("2")) {
showAlert("Paypal API call failed. Account not found. Unilateral receiver not allowed in chained payment is restricted.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
// showAlert(getString(R.string.no_connection_server), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_connection_server, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
}
};
/**
* Set order view data from web servicie responce
**/
private void setOrderView(JSONArray items) {
try {
mLinearLayoutOrderDetails.removeAllViews();
//mArrayListMethod.clear();
for (int i = 0; i < items.length(); i++) {
JSONObject mJsonObject = items.getJSONObject(i);
viewOrderData = getLayoutInflater().inflate(R.layout.single_chkout_order_listing, null);
TextView mTvName = (TextView) viewOrderData.findViewById(R.id.tv_order_name);
TextView mTvPrice = (TextView) viewOrderData.findViewById(R.id.tv_order_price);
TextView mTvQuan = (TextView) viewOrderData.findViewById(R.id.tv_order_quantity);
TextView mTvSubTot = (TextView) viewOrderData.findViewById(R.id.tv_order_sub_total);
mTvName.setText(mJsonObject.getString("name"));
mTvPrice.setText(mJsonObject.getString("price"));
mTvQuan.setText(mJsonObject.getString("quantity"));
mTvSubTot.setText(mJsonObject.getString("rowtotal"));
mLinearLayoutOrderDetails.addView(viewOrderData);
}
} catch (Exception e) {
e.printStackTrace();
}
}

android.view.windowmanager$badtokenexception unable to add window -- token null is not for an application

I have researched this error on StackOverflow and tried all the suggestions but still have the error. App tries to load and I can see the home screen behind several of the alerts and an error that the app closed.
Things I've tried:
adding to Manifest -
in MainActivity, ensuring I'm using "this" in lieu of other references
adding to AlertDialog -
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
NOTE: I've also commented out out everything from the onCreate() in MainActivity after setContentView(R.layout.activity_main); and still have the error. I suspect the issue is directly related to how I'm using my fragment and the tjerk. ActionSlideExpandableListView menu.
My code:
MainActivity
public class MainActivity extends Activity implements DataPasser {
private final String LOGCAT = "MAINACTIVITY.LOGCAT";
private DrawerLayout mDrawerLayout;
Toolbar toolbar;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
Fragment fragment = null;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Menu menuMain;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
// --------------------------------------------------
private final String PREF_NAME = "band_wit";
String firstLaunch = "firstLaunch", itemPosition = "2";
private TCPdump tcpdump = null;
private TCPdumpHandler tcpDumpHandler = null;
static public String local_Ip_Address;
DBHelper dbHelper;
FragmentManager fragmentManager;
private MyReceiver receiver;
private static final int VPN_REQUEST_CODE = 0x0F;
private boolean waitingForVPNStart;
public static String APP_UID;
public static String NETFLIX_APP_UID;
public static String FACEBOOK_APP_UID;
private BroadcastReceiver vpnStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocalVPNService.BROADCAST_VPN_STATE.equals(intent.getAction())) {
if (intent.getBooleanExtra("running", false))
waitingForVPNStart = false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = DBHelper.newInstance(this);
local_Ip_Address = getLocalIpAddress();
// Local VPN
LocalBroadcastManager.getInstance(this).registerReceiver(
vpnStateReceiver,
new IntentFilter(LocalVPNService.BROADCAST_VPN_STATE));
// ====
Intent tcp_Dump_Inent = new Intent(MainActivity.this,TcpDumpService.class);
startService(tcp_Dump_Inent);
/* start service for download manager */
startService(new Intent(this, MyDownloaderMangerService.class));
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// Find People
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// Pages
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// ** setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(this,
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar,
//R.drawable.ic_drawer,
R.string.app_name,
R.string.app_name)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
startService(new Intent(this, MyService.class));
// Run when application first time launched
Const.preferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
boolean isFirstTime = Const.preferences.getBoolean(firstLaunch, true);
if (isFirstTime) {
Const.preferences.edit().putBoolean(firstLaunch, false).commit();
addBgData(Const.preferences);
setInitialDataBucket();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.splash_screen, null);
builder.setView(view);
dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
APP_UID = myAppUid("com.oda.bandwit");
NETFLIX_APP_UID = myAppUid("com.netflix.mediaclient");
FACEBOOK_APP_UID = myAppUid("com.facebook.katana");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
try {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new MyReceiver();
registerReceiver(receiver, filter);
} catch (Exception e) {
// TODO: handle exception
}
startVPN();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try {
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int fragment = 0;
Fragment f = this.getFragmentManager().findFragmentById(
R.id.frame_container);
if (f instanceof HomeFragment) {
fragment = 0;
} else if (f instanceof GeneralSettingsFragment) {
fragment = 1;
} else if (f instanceof ApplicationSettinsFragment) {
fragment = 2;
} else if (f instanceof NetworkSettingsFragment) {
fragment = 3;
} else if (f instanceof GraphAnalysisFragment) {
fragment = 4;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.menuToday:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Today");
itemPosition = "0";
displayView(fragment);
return true;
case R.id.menuThisWeek:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Current Week");
itemPosition = "1";
displayView(fragment);
return true;
case R.id.menuThisMonth:
menuMain.findItem(R.id.menuSelectedItem).setTitle("Current Month");
itemPosition = "2";
displayView(fragment);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menuMain = menu;
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menuMain.findItem(R.id.menuToday).setVisible(!drawerOpen);
menuMain.findItem(R.id.menuThisWeek).setVisible(!drawerOpen);
menuMain.findItem(R.id.menuThisMonth).setVisible(!drawerOpen);
menuMain.getItem(Integer.parseInt(itemPosition)).setChecked(true);
return super.onPrepareOptionsMenu(menuMain);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
try {
fragment = new HomeFragment("" + itemPosition);
callFragment(position);
} catch (Exception e) {
e.getMessage();
}
break;
case 1:
fragment = new ApplicationSettinsFragment();
callFragment(position);
break;
case 2:
startActivity(new Intent(MainActivity.this, GraphicalAnalysis.class));
break;
case 3:
sendMail();
break;
case 4:
dialog = new Dialog(MainActivity.this);
Toast.makeText(MainActivity.this, "Change Limit", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Threshold");
ListView list=new ListView(MainActivity.this);
ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
new String[]{"5","10","15","20","25","30","35","40","45","50","55","60","65","70","75","80","85","90","95","100","105","110","115","120","125","130","135","140","145","150","155","160","165","170","175","180","185","190","195","200"});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Toast.makeText(MainActivity.this,
"Now Threshold " + (position + 1) * 5 +" is set",
Toast.LENGTH_SHORT).show();
LocalVPNService.netFlixMaxVal = (position + 1) * 5;
navDrawerItems.get(4).setCount(""+LocalVPNService.netFlixMaxVal);
MainActivity.this.adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
builder.setView(list);
dialog=builder.create();
dialog.show();
break;
case 5:
fragment = new WhatsHotFragment();
callFragment(position);
break;
default:
break;
}
}
Dialog dialog;
private void callFragment(int position) {
if (fragment != null) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VPN_REQUEST_CODE && resultCode == RESULT_OK) {
startService(new Intent(this, LocalVPNService.class));
}
}
}
Home Fragment
public class HomeFragment extends Fragment {
Boolean checked;
DBHelper dbHelper;
String filterFlag = "", networkTypeSelected = "";
CustomAdapter adap = null;
OnClickListener clickListener;
TextView tvNetworkType;
SharedPreferences prefs;
private static String FILENAME = "mlogs.txt";
public HomeFragment() {
// TODO Auto-generated constructor stub
}
public HomeFragment(String dataFilter) {
filterFlag = dataFilter;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_home,
container, false);
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
try {
dbHelper = DBHelper.newInstance(getActivity());
tvNetworkType = (TextView) rootView
.findViewById(R.id.tvNetworkTypeHome);
clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Editor edit = prefs.edit();
if (v.getId() == R.id.btnCellularHome) {
checked = false;
tvNetworkType.setText("Cellular Data");
edit.putString("network", "0");
} else if (v.getId() == R.id.btnWifiHome) {
checked = true;
tvNetworkType.setText("Wi-fi Data");
edit.putString("network", "1");
}
edit.commit();
setListViewData(rootView);
}
};
rootView.findViewById(R.id.btnCellularHome).setOnClickListener(
clickListener);
rootView.findViewById(R.id.btnWifiHome).setOnClickListener(
clickListener);
if (prefs.getString("network", "0").equalsIgnoreCase("1")) {
checked = true;
tvNetworkType.setText("Wi-fi Data");
} else {
tvNetworkType.setText("Cellular Data");
checked = false;
}
setListViewData(rootView);
} catch (Exception e) {
e.getMessage();
}
TextView ytdata = (TextView) rootView.findViewById(R.id.ytdata);
TcpDumpUtills tcpDumpUtills = new TcpDumpUtills(getActivity());
ytdata.setText(StringUtils.formatToMultiplier(tcpDumpUtills
.getAppsConsumedData("com.google.android.youtube")));
ytdata.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
writeDataToFile(log.toString());
} catch (IOException e) {
}
}
});
super.onSaveInstanceState(savedInstanceState);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//mContext = activity;
}
public void writeDataToFile(String data){
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getActivity(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Logss", "File write failed: " + e.toString());
}
}
public ListAdapter getData() {
Resources res = getResources();
ArrayList<ListModel> arr = new ArrayList<ListModel>();
ArrayList<ListModel> arrFinal = new ArrayList<ListModel>();
String networkType = "";
if (checked) {
networkType = "1";
} else {
networkType = "0";
}
PackageManager manager = getActivity().getPackageManager();
arr = dbHelper.getAppsDataAccordingToNetworkType(networkType);
if (arr.size() >= 1) {
for (ListModel modelGetter : arr) {
ListModel modelSetter = new ListModel();
String packageName = modelGetter.getAppName();
// Setting App Name
try {
ApplicationInfo appInfo = manager.getApplicationInfo(
modelGetter.getAppName(), 0);
String appName = "" + manager.getApplicationLabel(appInfo);
modelSetter.setAppName(appName);
// Setting Total Data Consumned by the app
long appTotalData = getTotalDataPerApp(modelGetter
.getAppName());
modelSetter.setDataConsumed(appTotalData);
String appTotalDataStr = CommonFunctions
.humanReadableByteCount(appTotalData, false);
modelSetter.setTotalData(appTotalDataStr);
// Setting Total Data as per the network selected
long networkDataPerApp = getDailyNetworkDataPerApp(
modelGetter.getNetworkData(), packageName);
String networkDataStr = CommonFunctions
.humanReadableByteCount(networkDataPerApp, false);
modelSetter.setNetworkData(networkDataStr);
double percd = networkDataPerApp / (double) appTotalData
* 100;
int perc = (int) percd;
modelSetter.setPercenatge(perc);
// Setting App Icon
Drawable draw = manager.getApplicationIcon(modelGetter
.getAppName());
modelSetter.setDrawable(draw);
// Setting Today's Data
long appTodaysData = getUsageData(packageName);
String appTodayDataStr = CommonFunctions
.humanReadableByteCount(appTodaysData, false);
modelSetter.setTodaysData(appTodayDataStr);
Calendar cal = Calendar.getInstance();
long dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
long dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
long time = cal.get(Calendar.HOUR_OF_DAY);
long appConsumptionRate = getConsumptionRate(cal,
appTotalData);
String appConsumptionDataStr = CommonFunctions
.humanReadableByteCount(appConsumptionRate, false);
if (filterFlag.equalsIgnoreCase("0")) {
appConsumptionDataStr = appConsumptionDataStr + " /hr";
} else if (filterFlag.equalsIgnoreCase("1")) {
appConsumptionDataStr = appConsumptionDataStr + " /day";
}else if (filterFlag.equalsIgnoreCase("2")) {
appConsumptionDataStr = appConsumptionDataStr + " /day.";
}
modelSetter.setConsumptionRate(appConsumptionDataStr);
// Setting Forecast Data
long appForecastData = getForecastData(appConsumptionRate,
dayOfMonth, dayOfWeek, time, appTotalData);
String appForecastDataStr = CommonFunctions
.humanReadableByteCount(appForecastData, false);
modelSetter.setForecastData(appForecastDataStr);
arrFinal.add(modelSetter);
} catch (Exception e) {
e.getMessage();
}
}
} else {
ListModel modelSetter = new ListModel();
modelSetter.setAppName("No Data");
modelSetter.setConsumptionRate("0.0 KB");
modelSetter.setForecastData("0.0 KB");
modelSetter.setNetworkData("0.0 KB");
modelSetter.setTodaysData("0.0 KB");
modelSetter.setTotalData("0.0 KB");
arrFinal.add(modelSetter);
}
Collections.sort(arrFinal, new Comparator<ListModel>() {
#Override
public int compare(ListModel lhs, ListModel rhs) {
// TODO Auto-generated method stub
return lhs.getDataConsumed() > rhs.getDataConsumed() ? -1
: lhs.getDataConsumed() < rhs.getDataConsumed() ? 1
: 0;
}
});
adap = new CustomAdapter(getActivity(), arrFinal, res, networkType);
adap.notifyDataSetChanged();
return adap;
}
public void setListViewData(View view) {
try {
ListAdapter adap = getData();
ActionSlideExpandableListView list = (ActionSlideExpandableListView) view
.findViewById(R.id.list);
list.setAdapter(adap);
list.setSmoothScrollbarEnabled(true);
// listen for events in the two buttons for every list item.
// the 'position' var will tell which list item is clicked
} catch (Exception e) {
e.getMessage();
}
}
private long getTotalDataPerApp(String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyTotalDataPerApp(sDate, eDate, packageName);
return data;
}
private long getDailyNetworkDataPerApp(String networkType,
String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyNetworkDataPerApp(sDate, eDate,
networkType, packageName);
return data;
}
private long getUsageData(String packageName) {
String[] arr = CommonFunctions.getDateAccordingToDuration(filterFlag);
String sDate = arr[0];
String eDate = arr[1];
long data = dbHelper.getDailyTotalDataPerApp(sDate, eDate, packageName);
return data;
}
private long getForecastData(long cRate, long dayOfMonth, long dayOfWeek,
long time, long appTotalData) {
long output = 0;
if (filterFlag.equalsIgnoreCase("0")) {
output = (cRate * (24 - time)) + appTotalData;
} else if (filterFlag.equalsIgnoreCase("1")) {
long leftDaysOfWeek = 7 - dayOfWeek;
output = (cRate * leftDaysOfWeek) + appTotalData;
} else if (filterFlag.equalsIgnoreCase("2")) {
long leftDaysOfMonth = 31 - dayOfMonth;
output = (cRate * leftDaysOfMonth) + appTotalData;
}
return output;
}
private long getConsumptionRate(Calendar cal, long totalData) {
long output = 0;
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int time = cal.get(Calendar.HOUR_OF_DAY);
if (filterFlag.equalsIgnoreCase("0")) {
output = totalData / time;
} else if (filterFlag.equalsIgnoreCase("1")) {
output = totalData / dayOfWeek;
} else if (filterFlag.equalsIgnoreCase("2")) {
output = totalData / dayOfMonth;
}
return output;
}
public ListAdapter buildDummyData() {
final int SIZE = 20;
String[] values = new String[SIZE];
for (int i = 0; i < SIZE; i++) {
values[i] = "Item " + i;
}
return new ArrayAdapter<String>(getActivity(),
R.layout.expandable_list_item, R.id.tvAppName, values);
}
}
Crash Log
11-19 21:33:24.010 12557-12557/com.oda.bandwit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.oda.bandwit, PID: 12557
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:682)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.oda.bandwit.TcpDumpService.startTCPdump(TcpDumpService.java:98)
at com.oda.bandwit.TcpDumpService.access$000(TcpDumpService.java:22)
at com.oda.bandwit.TcpDumpService$1.run(TcpDumpService.java:62)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

How to display images from sdcard smoothly in android

The below code is downloading images from a database showing into an sdcard. When previewing it was showing images. The first image showed perfectly, but from next image onwards it was showing like blank and loading images from the sdcard, but from sdcard it was not downloading image directly displaying images.
java
public class ImageGallery extends Activity {
Bundle bundle;
String catid, temp, responseJson;
JSONObject json;
ImageView imageViewPager;
// for parsing
JSONObject o1, o2;
JSONArray a1, a2;
int k;
Boolean toggleTopBar;
ArrayList<String> imageThumbnails;
ArrayList<String> imageFull;
public static int imagePosition=0;
SubsamplingScaleImageView imageView, imageViewPreview, fullImage ;
ImageView thumb1, back;
private LinearLayout thumb2;
RelativeLayout topLayout, stripeView;
RelativeLayout thumbnailButtons;
FrameLayout gridFrame;
public ImageLoader imageLoader;
//SharedPreferences data
SharedPreferences s1;
SharedPreferences.Editor editor;
int swipeCounter;
ParsingForFinalImages parsingObject;
int position_grid;
SharedPreferences p;
Bitmap bm;
int numOfImagesInsidee;
LinearLayout backLinLayout;
public static boolean isThumb2=false;
public static boolean isThumb1=false;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
//isThumb2=false;
toggleTopBar = false;
//position_grid=getIntent().getExtras().getInt("position");
thumbnailButtons = (RelativeLayout)findViewById(R.id.thumbnailButtons);
topLayout = (RelativeLayout)findViewById(R.id.topLayout);
//fullImage = (SubsamplingScaleImageView)findViewById(R.id.fullimage);
backLinLayout = (LinearLayout)findViewById(R.id.lin_back);
backLinLayout.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent io = new Intent(getBaseContext(), MainActivity.class);
// clear the previous activity and start a new task
// System.gc();
// io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(io);
finish();
}
});
ConnectionDetector cd = new ConnectionDetector(getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
thumb1 = (ImageView)findViewById(R.id.thumb1);
thumb2 = (LinearLayout)findViewById(R.id.thumb2);
stripeView = (RelativeLayout)findViewById(R.id.stripeView) ;
gridFrame = (FrameLayout)findViewById(R.id.gridFrame);
thumb1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
//fullImage.setVisibility(View.GONE);
thumb1.setClickable(false);
isThumb1=true;
isThumb2=false;
Log.i("Thumb Position 1",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new GridFragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
thumb2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
// stripeView.setVisibility(View.VISIBLE);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
// fullImage.setVisibility(View.GONE);
thumb1.setClickable(true);
isThumb2=true;
isThumb1=false;
Log.i("Thumb Position 2",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new ImageStripeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
// allow networking on main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/*bundle = getIntent().getExtras();
catid = bundle.getString("catid");*/
// Toast.makeText(getBaseContext(), catid, Toast.LENGTH_LONG).show();
// making json using the catalogue id we got
p = getSharedPreferences("gridData", Context.MODE_APPEND);
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedListPos = p.getInt("clickedPosition", 0);
imageViewPreview = (SubsamplingScaleImageView)findViewById(R.id.preview);
imageThumbnails = new ArrayList<String>();
imageFull = new ArrayList<String>();
s1 = this.getSharedPreferences("data", Context.MODE_APPEND);
editor = s1.edit();
Log.d("catidfnl", catid);
numOfImagesInsidee = p.getInt("numberOfItemsSelectedFromGrid1", 0);
Log.d("blingbling2", String.valueOf(numOfImagesInsidee));
// adding downloaded images to arraylist
for(int m=0;m<numOfImagesInsidee;m++){
imageThumbnails.add(Environment.getExternalStorageDirectory()+"/"+"thumbImage" + catid + m+".png");
imageFull.add(Environment.getExternalStorageDirectory()+"/"+"fullImage" + catid + m+".png");
// imageFull.add("file://" + Environment.getExternalStorageDirectory() + "/" + "fullImage32.png");
}
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// code to display image in a horizontal strip starts here
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for (int i = 0; i < imageThumbnails.size(); i++) {
imageView = new SubsamplingScaleImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
// Picasso.with(this).load("file://"+imageThumbnails.get(i)).into(imageView);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.width = 200;
params.height = 200;
imageView.setLayoutParams(params);
imageView.setZoomEnabled(false);
imageView.setDoubleTapZoomScale(0);
imageView.setImage(ImageSource.uri(imageThumbnails.get(0)));
imageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView.setZoomEnabled(false);
imageViewPreview.setImage(ImageSource.uri(imageFull.get(view.getId())));
imageView.recycle();
imageViewPreview.recycle();
}
});
}
// code to display image in a horizontal strip ends here
imageViewPreview.setZoomEnabled(false);
/*imageViewPreview.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageViewPreview.setZoomEnabled(false);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}
});*/
imageViewPreview.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.d("yo click", "single");
}
#Override
public void onDoubleClick(View v) {
Log.d("yo click", "double");
}
});
}
public abstract class DoubleClickListener implements View.OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
long lastClickTime = 0;
#Override
public void onClick(View v) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
onDoubleClick(v);
} else {
onSingleClick(v);
}
lastClickTime = clickTime;
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
// #Override
// public void onBackPressed() {
// Intent io = new Intent(getBaseContext(), MainActivity.class);
// // clear the previous activity and start a new task
// super.onBackPressed();
// finish();
// // System.gc();
// // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(io);
// }
#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_image_gallery, menu);
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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
/* private int[] mImages = new int[] {
R.drawable.scroll3,
R.drawable.scroll1,
R.drawable.scroll2,
R.drawable.scroll4
};*/
/* private String[] description=new String[]
{
"One","two","three","four"
};
*/
#Override
public int getCount() {
Log.i("Image List Size", "" + imageFull.size());
return imageFull.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
// ImageLoader loader = new ImageLoader(context, 1);
// loader.DisplayImage(ImageSource.uri(imageFull.get(imagePosition)),imageView,imagePosition,new ProgressDialog(context));
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// for placeholder
// fullImage.setImage(ImageSource.resource(R.drawable.tan2x));
if(!GridFragment2.isSelectedGrid2&&!ImageStripeFragment.isImageStripe) {
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
/* else if(!ImageStripeFragment.isImageStripe)
{
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
else if(ImageStripeFragment.isImageStripe)
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
}*/
else
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
//viewPager.removeAllViews();
}
// ImageView imageViewPager = new ImageView(context);
// ImageView imageViewPager = new ImageView(getApplicationContext());
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
GridFragment2.isSelectedGrid2=false;
ImageStripeFragment.isImageStripe=false;
// Log.i("Image Resource", "" + ImageSource.uri(imageFull.get(position)));
// imageViewPager.setImageBitmap(BitmapFactory.decodeFile(imageFull.get(position)));
// imageViewPager.setImageBitmap(myBitmap);
// fullImage.setImage(ImageSource.bitmap(bmImg));
//imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
/*int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);*/
/*imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
if(position==3)
{
}*/
// Log.i("Image Position",""+position);
/*text.setText(description[position]);
Log.i("Text Position",""+position);*/
/*switch(position)
{
case 0:
String pos=String.valueOf(position);
text.setText(pos);
break;
case 1:
String pos1=String.valueOf(position);
text.setText(pos1);
break;
case 2:
String pos2=String.valueOf(position);
text.setText(pos2);
break;
case 3:
String pos3=String.valueOf(position);
text.setText(pos3);
break;
}*/
fullImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toggleTopBar == false) {
// thumbnailButtons.setVisibility(View.GONE);
thumbnailButtons.animate()
.translationY(-2000)
.setDuration(1000)
.start();
toggleTopBar = true;
} else if (toggleTopBar == true) {
// thumbnailButtons.setVisibility(View.VISIBLE);
thumbnailButtons.animate()
.translationY(0)
.setDuration(1000)
.start();
toggleTopBar = false;
}
}
});
((ViewPager) container).addView(fullImage, 0);
return fullImage;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
/* #Override
public void destroyItem(View collection, int position, Object o) {
Log.d("DESTROY", "destroying view at position " + position);
View view = (View) o;
((ViewPager) collection).removeView(view);
view = null;
}*/
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
This will be the best approach for your Solution,Try using Universal Image Loader.
Features:
Multithread image loading (async or sync)
Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
Image caching in memory and/or on disk (device's file system or SD card)
Listening loading process (including downloading progress)
Find link here : https://github.com/nostra13/Android-Universal-Image-Loader

Categories