How to display images from sdcard smoothly in android - java

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

Related

Android studio, loading 2 spinners with different data from different MYSQL databases

My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.

java.lang.OutOfMemoryError with ArrayList.addAll()

I have a list of threads which I have paginated to use an endless scroll the issue I'm having (well my users) is an OutOfMemoryError: Failed to allocate a [x] byte allocation with [y] free bytes and [z] until OOM. the x, y and z attribute is different per user but the cause of the bug is always in the same place and it's when I refresh the posts. I'm completely out of my depth here as I have no idea how to optimise my code or make it so this doesn't happen. As it's the biggest crash on my app at the moment. I've posted my PostFragment below please see the refreshPosts(ArrayList<Posts> newObjects) method as this is where the crash is happening.
public class PostFragment extends Fragment implements View.OnClickListener {
private View mRootView;
private GridLayoutManager mLayoutManager;
private ThreadItem mThreads;
private PostItem mPost;
private PostAdapter mAdapter;
private PostResponse mData;
private EmoticonResponse mEmoticon;
private PostFeedDataFactory mDataFactory;
private EmoticonFeedDataFactory mEmoticonDataFactory;
private static PostFragment mCurrentFragment;
private int REQUEST_CODE;
//Flip
private boolean isFlipped = false;
private Animation flipAnimation;
#BindView(R.id.postsRecyclerView)
RecyclerView mRecyclerView;
#BindView(R.id.toolbarForPosts)
Toolbar mToolbar;
#BindView(R.id.threadText)
TextView mThreadText;
#BindView(R.id.flipText)
TextView mFlipTextView;
#BindView(R.id.shareText)
TextView mShareTextView;
#BindView(R.id.replyText)
TextView mReplyTextView;
#BindView(R.id.scrimColorView)
View mBackgroundView;
#BindView(R.id.fabMenu)
FloatingActionButton mFabMenu;
#BindView(R.id.flipFab)
FloatingActionButton mFlipFab;
#BindView(R.id.shareFab)
FloatingActionButton mShareFab;
#BindView(R.id.replyFab)
FloatingActionButton mReplyFab;
//Collapsing Toolbar
#BindView(R.id.postParentAppBarLayout)
AppBarLayout postAppBarLayout;
#BindView(R.id.postCollapseToolbar)
CollapsingToolbarLayout postCollapseToolbarLayout;
#BindView(R.id.mainImageContainer)
ViewGroup mainContainer;
//Back to top
#BindView(R.id.backToTopButton)
Button mBackToTop;
public static boolean isFromReply;
//FAB
private boolean mIsFabOpen = false;
private Animation fab_open, fab_close, rotate_forward, rotate_backward;
//Pagination
private int mCurrentPage = 1;
private ArrayList<Posts> postList = new ArrayList<>();
private boolean mIsLoading = false;
private boolean mIsLastPage = false;
public static PostFragment newInstance(#NonNull ThreadItem threadItem) {
Bundle args = new Bundle();
args.putParcelable("ThreadItem", Parcels.wrap(threadItem));
mCurrentFragment = new PostFragment();
mCurrentFragment.setArguments(args);
isFromReply = false;
return mCurrentFragment;
}
public static PostFragment newPostInstance(#NonNull PostItem postItem) {
Bundle args = new Bundle();
args.putParcelable("PostItemFromCompose", Parcels.wrap(postItem));
mCurrentFragment = new PostFragment();
mCurrentFragment.setArguments(args);
isFromReply = true;
return mCurrentFragment;
}
public PostFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_post, container, false);
if (savedInstanceState == null) {
ButterKnife.bind(this, mRootView);
initUI();
}
return mRootView;
}
private void initUI() {
//UI Setup
mLayoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(mLayoutManager);
mDataFactory = new PostFeedDataFactory(getActivity());
mEmoticonDataFactory = new EmoticonFeedDataFactory(getActivity());
TextView textThreadTopic = (TextView) mRootView.findViewById(R.id.threadTopic);
TextView textNumPosts = (TextView) mRootView.findViewById(R.id.numPosts);
//FAB onClick Set-Up
mFabMenu.setOnClickListener(this);
mShareFab.setOnClickListener(this);
mReplyFab.setOnClickListener(this);
mFlipFab.setOnClickListener(this);
//FAB Animation Set up
fab_open = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.rotate_backward);
//Toolbar
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.ic_back_white);
mToolbar.invalidate();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
//Load Parcel
Intent intent = getActivity().getIntent();
mThreads = Parcels.unwrap(getArguments().getParcelable("ThreadItem"));
mPost = Parcels.unwrap(getArguments().getParcelable("PostItemFromCompose"));
if (mThreads != null) {
if (mThreads.getName() != null) {
mThreadText.setText(mThreads.getName());
}
if (mThreads.getTopic_name() != null) {
textThreadTopic.setText(mThreads.getTopic_name());
}
if (mThreads.getNum_posts() != null) {
int numPosts = Integer.parseInt(mThreads.getNum_posts());
if (numPosts > 1000) {
textNumPosts.setText("1K");
} else {
textNumPosts.setText(mThreads.getNum_posts());
}
}
}
postAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
postCollapseToolbarLayout.setTitle("Threads");
mainContainer.setVisibility(View.INVISIBLE);
isShow = true;
} else if (isShow) {
postCollapseToolbarLayout.setTitle("");
isShow = false;
mainContainer.setVisibility(View.VISIBLE);
}
}
});
flipAnimation =
AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.flip);
loadData(true, 1);
}
private void loadData(final boolean firstLoad, int readDirection) {
if (isFromReply) {
if (mPost.getThread_id() != null) {
mDataFactory.getPostFeed(mPost.getThread_id(), readDirection, mCurrentPage,
new PostFeedDataFactory.PostFeedDataFactoryCallback() {
#Override
public void onPostDataReceived(PostResponse response) {
mData = response;
if (mData.getItems() != null) {
for (int i = 0; i < mData.getItems().size(); i++) {
Posts singlePost = response.getItems().get(i);
postList.add(singlePost);
}
if (firstLoad) {
mIsLoading = false;
mData.getItems().clear();
mData.getItems().addAll(postList);
mEmoticonDataFactory.getEmoticonFeed(
new EmoticonFeedDataFactory.EmoticonFeedDataFactoryCallback() {
#Override
public void onEmoticonDataReceived(EmoticonResponse response) {
mEmoticon = response;
populateUIWithData();
}
#Override
public void onEmoticonDataFailed(Exception exception) {
}
});
} else {
mIsLoading = false;
refreshPosts(postList);
}
if (mData.getItems().size() > 0) {
if (Integer.valueOf(mData.getTotalPosts()) >= response.getItems().size()) {
mCurrentPage++;
} else {
mIsLastPage = true;
}
}
}
}
#Override
public void onPostDataFailed(Exception exception) {
customToast("Error: " + exception.toString());
}
});
}
} else {
if (mThreads.getId() != null)
mDataFactory.getPostFeed(mThreads.getId(), readDirection, mCurrentPage,
new PostFeedDataFactory.PostFeedDataFactoryCallback() {
#Override
public void onPostDataReceived(PostResponse response) {
mData = response;
if (mData.getItems() != null) {
for (int i = 0; i < mData.getItems().size(); i++) {
Posts singlePost = response.getItems().get(i);
postList.add(singlePost);
}
if (firstLoad) {
mIsLoading = false;
mData.getItems().clear();
mData.getItems().addAll(postList);
mEmoticonDataFactory.getEmoticonFeed(
new EmoticonFeedDataFactory.EmoticonFeedDataFactoryCallback() {
#Override
public void onEmoticonDataReceived(EmoticonResponse response) {
mEmoticon = response;
populateUIWithData();
}
#Override
public void onEmoticonDataFailed(Exception exception) {
}
});
} else {
mIsLoading = false;
refreshPosts(postList);
}
if (mData.getItems().size() > 0) {
if (Integer.valueOf(mData.getTotalPosts()) >= response.getItems().size()) {
mCurrentPage++;
} else {
mIsLastPage = true;
}
}
}
}
#Override
public void onPostDataFailed(Exception exception) {
customToast("Error: " + exception.toString());
}
});
}
}
private void populateUIWithData() {
ImageButton moreOptionsButton = (ImageButton) mRootView.findViewById(R.id.moreOptions);
moreOptionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
popupMenu.inflate(R.menu.thread_options);
popupMenu.getMenu();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.watch:
WatchedThreadsRequestData watchedThreadsRequestData = new WatchedThreadsRequestData(getActivity());
watchedThreadsRequestData.setWatchedThread(mThreads.getId(), new WatchedThreadsRequestData.WatchedThreadsFeedback() {
#Override
public void onWatchedRequestReceived(ThreadResponse response) {
customToast("Thread watched");
}
#Override
public void onWatchedRequestFailed(Exception exception) {
customToast("Thread wasn't watched: " + exception.toString());
}
});
return true;
case R.id.shareThread:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, mThreads.getName() + " - " + Constants.LIVE_URL +
"talk/" + mThreads.getTopic_url() + '/' + mThreads.getThread_url());
sharingIntent.setType("text/plain");
getActivity().startActivity(Intent.createChooser(sharingIntent, "Share via"));
return true;
case R.id.hideThread:
customToast("Hide: coming soon");
return true;
default:
customToast("Somethings Wrong");
return true;
}
}
});
setForceShowIcon(popupMenu);
popupMenu.show();
}
});
if (mAdapter == null) {
mAdapter = new PostAdapter(getActivity(), mData, mEmoticon);
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setData(mData.getItems());
mAdapter.notifyDataSetChanged();
}
mRecyclerView.addOnScrollListener(paginationListener);
}
public static void setForceShowIcon(PopupMenu popupMenu) {
try {
Field[] fields = popupMenu.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popupMenu);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private RecyclerView.OnScrollListener paginationListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
boolean hasEnded = newState == SCROLL_STATE_IDLE;
if (hasEnded) {
mFabMenu.show();
mFabMenu.setClickable(true);
} else {
if (mIsFabOpen)
closeMenu();
mFabMenu.hide();
mFabMenu.setClickable(false);
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
if (!mIsLoading && !mIsLastPage) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount) {
loadMoreItems();
}
}
//Back to top
if (mLayoutManager.findLastVisibleItemPosition() == totalItemCount - 1) {
mBackToTop.setVisibility(View.VISIBLE);
mBackToTop.setClickable(true);
mBackToTop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayoutManager.scrollToPositionWithOffset(0,0);
}
});
} else {
mBackToTop.setVisibility(View.GONE);
mBackToTop.setClickable(false);
}
}
};
private void loadMoreItems() {
if (!isFlipped) {
mIsLoading = true;
loadData(false, 1);
} else {
mIsLoading = true;
loadData(false, -1);
}
}
private void refreshPosts(ArrayList<Posts> newObjects) {
postList.addAll(newObjects);
populateUIWithData();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.fabMenu:
animateFAB();
break;
case R.id.shareFab:
share();
break;
case R.id.replyFab:
reply();
break;
case R.id.flipFab:
flip();
break;
}
}
public void animateFAB() {
if (mIsFabOpen) {
closeMenu();
} else {
mFabMenu.startAnimation(rotate_forward);
mReplyFab.startAnimation(fab_open);
mShareFab.startAnimation(fab_open);
mFlipFab.startAnimation(fab_open);
mReplyFab.setClickable(true);
mShareFab.setClickable(true);
mFlipFab.setClickable(true);
mFlipTextView.setVisibility(View.VISIBLE);
mShareTextView.setVisibility(View.VISIBLE);
mReplyTextView.setVisibility(View.VISIBLE);
mBackgroundView.setVisibility(View.VISIBLE);
mIsFabOpen = true;
}
}
private void closeMenu() {
mFabMenu.startAnimation(rotate_backward);
mReplyFab.startAnimation(fab_close);
mShareFab.startAnimation(fab_close);
mFlipFab.startAnimation(fab_close);
mReplyFab.setClickable(false);
mShareFab.setClickable(false);
mFlipFab.setClickable(false);
mFlipTextView.setVisibility(View.INVISIBLE);
mShareTextView.setVisibility(View.INVISIBLE);
mReplyTextView.setVisibility(View.INVISIBLE);
mBackgroundView.setVisibility(View.INVISIBLE);
mIsFabOpen = false;
}
private void reply() {
PreferenceConnector.writeString(getActivity().getApplicationContext(), "threadID", mThreads.getId());
PreferenceConnector.writeString(getActivity().getApplicationContext(), "threadTitle", mThreads.getName());
if (PreferenceConnector.readString(getActivity(), "authToken") == null ||
PreferenceConnector.readString(getActivity(), "authToken").equalsIgnoreCase("skip")) {
final AlertDialog.Builder loginDialog = new AlertDialog.Builder(getActivity());
loginDialog.setTitle("Please log in");
loginDialog.setMessage("You need to be logged in to reply");
loginDialog.setPositiveButton("Log in", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
loginDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
loginDialog.show();
} else {
closeMenu();
Intent intent = new Intent(getActivity().getApplicationContext(), NewPostActivity.class);
intent.putExtra("Threads", Parcels.wrap(mThreads));
getActivity().finish();
startActivityForResult(intent, REQUEST_CODE);
}
}
private void share() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, mThreads.getName() + " - " + Constants.LIVE_URL +
"talk/" + mThreads.getTopic_url() + '/' + mThreads.getThread_url());
sharingIntent.setType("text/plain");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
private void flip() {
if (!isFlipped) {
mAdapter.clearAll();
isFlipped = true;
mRecyclerView.startAnimation(flipAnimation);
loadData(false, -1);
closeMenu();
} else {
mAdapter.clearAll();
isFlipped = false;
mRecyclerView.startAnimation(flipAnimation);
loadData(true, 1);
closeMenu();
}
}
private void customToast(String toastMessage) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) getActivity().findViewById(R.id.toastContainer));
TextView customToastText = (TextView) layout.findViewById(R.id.customToastText);
customToastText.setText(toastMessage);
Toast toast = new Toast(getActivity().getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 25);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
#Override
public void onResume() {
super.onResume();
if (mData != null && mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if (mIsFabOpen) {
closeMenu();
} else {
getActivity().finish();
}
return true;
}
return false;
}
});
}
public void updateView() {
mAdapter.notifyDataSetChanged();
}
}
Thanks in advance once again.
Your problem basically boils down to this:
private void refreshPosts(ArrayList<Posts> newObjects) {
postList.addAll(newObjects);
populateUIWithData();
}
The list can only get bigger, never smaller. If the server has lots and lots of posts, then OutOfMemory is pretty much inevitable.
One approach to solving this problem is to use an LRU (Least Recently Used) cache. There is a utility class you can use: android.util.LruCache.
An LRU Cache is essentially a Map. Items are stored with a key, like an ID. With an LRU cache, you put new items in, but once a pre-determined limit is reached, old items start getting pushed out to make room for new items.
This will save memory, but make a lot more management code for you.
Your adapter, instead of having a list of posts, will just have a list of the post IDs. This should be much easier on memory.
As the user scrolls and you collect more posts, you add the post ID to the list, and map the post into the LRU cache using the post ID.
When you bind to the list item view, you look up the post using the post's ID in the LRU cache.
If it's there, great. That's called a cache hit. Bind the post to the
list item view.
If not, then you have a cache miss. You have some work to do.
Start a server request to retrieve the post by ID. I see your current code just retrieves blocks of posts, so you'll need some new server code here.
When the request completes, put the post in the LRU cache and let the adapter know your item has changed using adapter.notifyItemChanged(). Unless the user has scrolled beyond it, the RecyclerView should try to bind with the list item view again. This time, you should get a cache hit.
This is the basic idea. I'd write some code, but I still have a lot of questions since I can't see your model classes, data factories, and adapter class.
Once you have it working, you have to tune the limit on the cache so that it's low enough not to overrun memory, but high enough that your hit/miss ratio isn't close to zero.
BTW, I noticed that you are making the mistake of creating a new adapter and handing it to the RecyclerView each time you get a block of posts. You should create your adapter once, keep a reference to it and update it. Have a method that adds a block of posts then calls notifyDataSetChanged().
Another idea for conserving memory is to use text compression. If the problem is more a result of a large average size of the post rather than a large number of posts, you might explore this idea in addition to the LRU cache.
The concept is that you could take posts over a certain size, write them into a buffer using a ZipOutputStream then save the buffer in memory. When it's time to display the post, you read the buffer with a ZipInputStream to uncompress the text. Here the issue is performance as the compression/decompression is pretty CPU-intensive. But if the problem is really long posts, this approach might be something to consider.
An even better approach: Only save the first part of the post as an "overview" display in the list. When the user clicks on the list item, retrieve the entire post from the server and display that in another page.

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)

Fragment Recycler view onclick show popup

i have an activity with recyclerview that extends fragment activity.
When an item is clicked from a recyerview, i want to get the title and display it as a pop up message.
i tried several ways but noting works. cam some one help me to do this TNX.
PickupActivity
public class PickupActivity extends AppCompatActivity implements View.OnClickListener{
private Toolbar toolbar;
private navigationDrawerFragment drawerFragment;
ApplicationEnvironmentURL applicationEnvironment;
ProgressDialog pDialog;
Context context;
String BASEURL;
String FilteredData;
String AllAgents;
public String ProfileId;
public String companyId;
public String profileToken;
private com.github.clans.fab.FloatingActionButton pik_fab1;
private com.github.clans.fab.FloatingActionButton pik_fab2;
private com.github.clans.fab.FloatingActionButton pik_fab3;
private com.github.clans.fab.FloatingActionButton pik_fab4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Dashboard");
setContentView(R.layout.activity_pickup);
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.app_bar_dashboard);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (navigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setup(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
pik_fab1 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_delete);
pik_fab2 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_close);
pik_fab3 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_assignto);
pik_fab4 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_pickup);
pik_fab1.setOnClickListener(this);
pik_fab2.setOnClickListener(this);
pik_fab3.setOnClickListener(this);
pik_fab4.setOnClickListener(this);
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
String islogged = prefs.getString("islogged", "Not defined");
String userid = prefs.getString("userid", "Not defined");
profileToken = prefs.getString("profileToken", "Not defined");
companyId = prefs.getString("companyId", "Not defined");
String companyName = prefs.getString("companyName", "Not defined");
ProfileId = prefs.getString("ProfileId", "Not defined");
Log.d("islogged : ", islogged);
Log.d("userid : ", userid);
Log.d("profileToken : ", profileToken);
Log.d("companyId : ", companyId);
Log.d("companyName : ", companyName);
Log.d("ProfileId : ", ProfileId);
getTickets(ProfileId, companyId, profileToken);
View newTicket = findViewById(R.id.newtic);
newTicket.setOnClickListener(onClickListener);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.pickup_pickup:
Log.d("Fab_clicked", "Pickup Ticket");
pickupTicketMessage("Are you sure you want to pickup the selected tickets?", "Confirm?");
break;
case R.id.pickup_close:
Log.d("Fab_clicked", "close tickets");
closeTicketMessage("Are you sure you want to close the selected tickets?", "Confirm?");
break;
case R.id.pickup_delete:
Log.d("Fab_clicked", "close tickets");
DeleteTicketMessage("Are you sure you want to delete the selected tickets?", "Confirm?");
break;
case R.id.pickup_assignto:
Log.d("Fab_clicked", "Assign to Agent");
try {
assignTicketstMessage("Select an agent");
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
/* Multiple Button on click event handle */
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.newtic:
// Create a login URl, before starting anything
if(isNetworkAvailable()){
Intent intentTicket = new Intent(PickupActivity.this, NewTicket.class);
startActivity(intentTicket);
} else {showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
break;
}
}
};
public void getTickets(String profileId, String companyId, String profileToken) {
if (isNetworkAvailable()) {
try {
setFilteredDataURL(companyId, profileId);
FilteredData = new getFilteredData().execute(profileToken).get();
// adding the filtered data to shared preferences for further use.
//adding user data to shared preferences.
SharedPreferences.Editor editor = getSharedPreferences("zupportdesk", MODE_PRIVATE).edit();
editor.putString("FilteredData", FilteredData);
editor.commit();
Log.d("ZF-Filtered_Data", FilteredData);
setTicketsURL(profileId, companyId);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new getNewTickets().execute(profileToken);
} else {
showErrorMessage("Please check your internet connection.", "No Connectivity!");
}
}
private void PickupTicket() throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray TicketsArray = new JSONArray();
List<Integer> selected_item = new ArrayList<>();
for (PickupTicketsItemObject ticket : PickupActivityFragment.support_ticket) {
if (ticket.isSelected()) {
selected_item.add(Integer.valueOf(ticket.getTicket_id()));
TicketsArray.put(Integer.valueOf(ticket.getTicket_id()));
}
}
Log.d("pickup_ticket_size", String.valueOf(selected_item.size()));
if(selected_item.size() < 1){
Log.d("pickup_ticket_size", "empty");
//Show Error Message
}else {
Log.d("pickup_ticket_size", "have tickets");
jsonObject.put("TicketID", TicketsArray);
jsonObject.put("ProfileId", ProfileId);
jsonObject.put("CompanyID", companyId);
setPickupTicketURI();
Log.d("ZF-PickupTicket", String.valueOf(jsonObject));
new TicketPickupRequest().execute(String.valueOf(jsonObject), profileToken);
}
}
private void showSuccessMessage(String data, String title){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// restart Activity
finish();
startActivity(getIntent());
}
})
.setIcon(R.drawable.notification_success)
.show();
}
private void assignTicketstMessage(String title) throws JSONException {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(title);
final List<String> agentList = new ArrayList<String>();
final List<String> agentProfileIDList = new ArrayList<String>();
if(AllAgents != null && !AllAgents.isEmpty() && !AllAgents.equals("null")) {
JSONArray jsonarray = new JSONArray(AllAgents);
int count = jsonarray.length();
Log.d("Full Agents", String.valueOf(count));
for (int k = 0; k < jsonarray.length(); k++) {
JSONObject jsonobject5 = jsonarray.getJSONObject(k);
Log.d("Agent object ", String.valueOf(jsonobject5));
agentList.add(jsonobject5.getString("FirstName"));
agentProfileIDList.add(jsonobject5.getString("ProfileId"));
}
String[] types = new String[agentList.size()];
for (int j = 0; j < agentList.size(); j++) {
types[j] = agentList.get(j);
}
b.setItems(types, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Selected_no ", String.valueOf(which));
Log.d("Selected_agent ", String.valueOf(agentList.get(which)));
Log.d("Selected_profile_id ", String.valueOf(agentProfileIDList.get(which)));
dialog.dismiss();
assignTicketstMessage2(String.valueOf(agentList.get(which)), String.valueOf(agentProfileIDList.get(which)));
}
});
b.show();
}
}
#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_main, 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) {
Intent i = new Intent(getApplicationContext(),Settings.class);
startActivity(i);
return true;
}
if(id == R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
//noinspection SimplifiableIfStatement
if (id == R.id.notification){
Intent i = new Intent(getApplicationContext(), Notifications.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void showErrorMessage(String data, String title) {
new AlertDialog.Builder(this.context)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.notification_red)
.show();
}
private void showErrorMessageNoInbox(String data, String title) {
new AlertDialog.Builder(this.context)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
})
.setIcon(R.drawable.notification_red)
.show();
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
......................... More
PickupActivityFragment
public class PickupActivityFragment extends Fragment {
public static ArrayList<PickupTicketsItemObject> support_ticket;
public static RecyclerView Ticketslist;
PickupActivity pick_up_activity;
public PickupActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_pickup_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pick_up_activity = new PickupActivity();
Ticketslist = (RecyclerView) view.findViewById(R.id.pickup_list);
Ticketslist.setLayoutManager(new LinearLayoutManager(getActivity()));
Ticketslist.setHasFixedSize(true);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pick_up_activity = new PickupActivity();
}
}
PickupTicketsAdapter
public class PickupTicketsAdapter extends RecyclerView.Adapter<PickupTicketsAdapter.ViewHolder> {
ArrayList<PickupTicketsItemObject> all_tickets;
public PickupTicketsAdapter(List<PickupTicketsItemObject> tickets) {
this.all_tickets = new ArrayList<>(tickets);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_pick_tickets, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.bindData(all_tickets.get(position));
//in some cases, it will prevent unwanted situations
holder.checkbox.setOnCheckedChangeListener(null);
//if true, your checkbox will be selected, else unselected
holder.checkbox.setChecked(all_tickets.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
all_tickets.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
}
#Override
public int getItemCount() {
return all_tickets.size();
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public ImageView priority;
public TextView sts_open;
public TextView sts_overdue;
public TextView tkt_from;
public TextView tkt_subject;
public TextView tkt_assignedto;
public TextView tkt_created_date;
public TextView txt_ticket_id;
public CheckBox checkbox;
public ViewHolder(View v) {
super(v);
checkbox = (CheckBox) v.findViewById(R.id.pick_checkbox);
priority = (ImageView) v.findViewById(R.id.priority_status_icon);
sts_open= (TextView) v.findViewById(R.id.tv_Tk_opn_status);
sts_overdue = (TextView) v.findViewById(R.id.tv_Tk_overdue);
tkt_from = (TextView) v.findViewById(R.id.tv_Tk_from);
tkt_subject = (TextView) v.findViewById(R.id.tv_Tk_subject);
tkt_assignedto = (TextView) v.findViewById(R.id.tv_Tk_Assignedto);
tkt_created_date = (TextView) v.findViewById(R.id.tv_Tk_Created_date);
txt_ticket_id = (TextView) v.findViewById(R.id.tv_Tk_TicketID);
}
public void bindData(PickupTicketsItemObject ticket) {
priority.setImageResource(ticket.getStatus_priority());
sts_open.setText(ticket.getStatus_open());
sts_overdue.setText(ticket.getStatus_overdue());
tkt_from.setText(ticket.getTicket_from());
tkt_subject.setText(ticket.getTicket_subject());
tkt_assignedto.setText(ticket.getTicket_assignedto());
tkt_created_date.setText(ticket.getTicket_created_date());
txt_ticket_id.setText(ticket.getTicket_id());
}
}
}
PickupTicketsItemObject
public class PickupTicketsItemObject {
private int status_priority;
private String status_open;
private String status_overdue;
private String ticket_from;
private String ticket_subject;
private String ticket_assignedto;
private String ticket_created_date;
private String ticket_id;
private boolean isSelected;
public PickupTicketsItemObject(){
}
public int getStatus_priority() {
return status_priority;
}
public String getStatus_open() {
return status_open;
}
public String getStatus_overdue() {
return status_overdue;
}
public String getTicket_from() {
return ticket_from;
}
public String getTicket_subject() {
return ticket_subject;
}
public String getTicket_assignedto() {
return ticket_assignedto;
}
public String getTicket_created_date(){return ticket_created_date;}
public String getTicket_id(){return ticket_id;}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public void setStatus_priority(int status_priority) {
this.status_priority = status_priority;
}
public void setStatus_open(String status_open) {
this.status_open = status_open;
}
public void setStatus_overdue(String status_overdue) {
this.status_overdue = status_overdue;
}
public void setTicket_from(String ticket_from) {
this.ticket_from = ticket_from;
}
public void setTicket_subject(String ticket_subject) {
this.ticket_subject = ticket_subject;
}
public void setTicket_assignedto(String ticket_assignedto) {
this.ticket_assignedto = ticket_assignedto;
}
public void setTicket_created_date(String ticket_created_date) {
this.ticket_created_date = ticket_created_date;
}
public void setTicket_id(String ticket_id) {
this.ticket_id = ticket_id;
}
}
public void onBindViewHolder(.....)
for particular TextView and use AlertDialog to show message inside adapter.
All you need to do is make changes in your adapter class
In your ViewHolder class, declare a CardView object as well.
Then in the onBindViewHolder method you can set the holder.cardview.onClickListener
You can use alert dialog builder for showing popups

Android IndexOutOfBoundsException Invalid index , size is 0

I'm creating an app that has an add to cart feature. I follow this tutorial and it works fine, but when i try to add the add to cart in the profile of the product instead in listview, i got an error which is IndexOutOfBoundsException Invalid index 51, size is 0
ProductDetails.java
public class ProductDetails extends Fragment {
static ConnectivityManager cm;
AlertDialog dialog2;
AlertDialog.Builder build;
TextView txtproduct,
txtprice,
txtcategorytype,
txtpieces,
txtdescription;
ImageView imgimage;
Button btncart,
btnview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_details, container, false);
final Controller ct = (Controller) getActivity().getApplicationContext();
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);// checking
build = new AlertDialog.Builder(getActivity()); // connectivity
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions)
.build();
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)// if connection is
// there screen goes
// to next screen
// else shows
// message
.isConnectedOrConnecting()
|| cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting()) {
Log.e("cm value",
""
+ cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting());
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
try {
JSONObject jsonObject1 = new JSONObject(String.valueOf(teaProfileId));
JSONObject jsonObject2 = new JSONObject(teaProfileName);
JSONObject jsonObject3 = new JSONObject(Float.toString(teaProfilePrice));
JSONObject jsonObject4 = new JSONObject(teaProfileImage);
JSONObject jsonObject5 = new JSONObject(teaProfileLabel);
JSONObject jsonObject6 = new JSONObject(String.valueOf(teaProfilePieces));
JSONObject jsonObject7 = new JSONObject(teaProfilePiecesType);
JSONObject jsonObject8 = new JSONObject(teaProfileDescription);
} catch (JSONException e) {
e.printStackTrace();
}
txtproduct = (TextView) rootView.findViewById(R.id.txtproduct);
txtprice = (TextView) rootView.findViewById(R.id.txtprice);
txtcategorytype = (TextView) rootView.findViewById(R.id.txtcategorytype);
txtpieces = (TextView) rootView.findViewById(R.id.txtpieces);
txtdescription = (TextView) rootView.findViewById(R.id.txtdescription);
txtproduct.setText(teaProfileName);
txtprice.setText(("PHP ") + String.format("%.2f", teaProfilePrice));
txtcategorytype.setText(teaProfileLabel);
txtpieces.setText((teaProfilePieces)+" "+(teaProfilePiecesType));
txtdescription.setText(teaProfileDescription.replaceAll("<br />",""));
imgimage = (ImageView)rootView.findViewById(R.id.imgimage);
final ProgressBar progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(teaProfileImage, imgimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
}
else {
build.setMessage("This application requires Internet connection. Would you connect to internet ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
dialog2 = build.create();
dialog2.show();
}
btncart = (Button) rootView.findViewById(R.id.btncart);
btncart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
Toast.makeText(getActivity(), teaProfileName+" was added to cart.", Toast.LENGTH_LONG).show();
ProductModel productsObject = ct.getProducts(teaProfileId);
ct.getCart().setProducts(productsObject);
}
});
btnview = (Button) rootView.findViewById(R.id.btnview);
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getActivity(),Screen1.class);
startActivity(in);
}
});
return rootView;
}
}
Controller.java
public class Controller extends Application {
private ArrayList<ProductModel> myproducts = new ArrayList<ProductModel>();
private ModelCart myCart = new ModelCart();
public ProductModel getProducts(int id){
return myproducts.get(id);
}
public void setProducts(ProductModel products){
myproducts.add(products);
}
public ModelCart getCart(){
return myCart;
}
}
ModelCart.java
public class ModelCart {
private ArrayList<ProductModel> cartItems = new ArrayList<ProductModel>();
public ProductModel getProducts(int position){
return cartItems.get(position);
}
public void setProducts(ProductModel Products){
cartItems.add(Products);
}
public int getCartsize(){
return cartItems.size();
}
public boolean CheckProductInCart(ProductModel aproduct){
return cartItems.contains(aproduct);
}
}
This is the error in logcat.
java.lang.IndexOutOfBoundsException: Invalid index 51, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
.Controller.getProducts(Controller.java:19)
.ProductDetails$4.onClick(ProductDetails.java:192)
This is line 19: return myproducts.get(id);
This is line 192: ProductModel productsObject = ct.getProducts(teaProfileId);

Categories