how to get current position in FragmentPagerAdapter? - java

I have an adapter that extends FragmentPagerAdapter and takes advantage of the ICS style actionBar. This actionbar has actions that take input from the currently selected page.
Specifically, I have a screenshot icon in the actionbar that takes the url of the current page and displays any screenshots from that url. However, I dont know how to retrieve the currently selected page.
How can I implement something like a
public int getActivePage() {
return position;
Im still working on the viewpager implementation, so my code is still heavily reliant on examples, so disregard the mess :P
The problem areas are marked below.
public class ListFragmentViewPagerActivity extends FragmentActivity {
ArrayList<String> URLS;
ArrayList<String> TITLES;
BroadcastReceiver receiver;
String threadTitle = null;
public static String threadUrl = null;
String type = null;
String threadAuthor = null;
String ident = null;
boolean isFav = false;
String author = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_view);
Bundle extras = getIntent().getExtras();
threadTitle = extras.getString("title");
threadUrl = extras.getString("url");
type = extras.getString("type");
ident = extras.getString("ident");
author = extras.getString("author");
try {
URLS = extras.getStringArrayList("urls");
TITLES = extras.getStringArrayList("titles");
} catch (Exception e) {
URLS = null;
}
final FDBAdapter db = new FDBAdapter(this);
db.open();
Cursor c = db.getAllFavs();
if (c.getCount()>0) {
if (c.getString(2).equals(threadTitle)) {
isFav = true;
}
try {
while (c.moveToNext()) {
Log.d("FAVS", c.getString(2));
if (c.getString(2).equals(threadTitle)) {
isFav = true;
}
}
} catch (Exception ep) {
ep.printStackTrace();
}
}
c.close();
db.close();
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager()));
TitlePageIndicator indicator = (TitlePageIndicator)findViewById( R.id.indicator );
indicator.setViewPager(pager);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
int icon = R.drawable.ic_launcher; // icon from resources
CharSequence tickerText = "Download ready!"; // ticker-text
long when = System.currentTimeMillis(); // notification time
CharSequence contentTitle = "OMG"; // expanded message title
CharSequence contentText = "Your download is finished!"; // expanded message text
Intent notificationIntent = new Intent(context, ExampleListFragment.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public class ExamplePagerAdapter extends FragmentPagerAdapter implements TitleProvider{
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return URLS.size();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ExampleListFragment();
// set arguments here, if required
Bundle args = new Bundle();
args.putString("url", URLS.get(position));
fragment.setArguments(args);
return fragment;
}
#Override
public String getTitle(int pos) {
return TITLES.get(pos);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.thread_menu, menu);
if (type.equals("xda")) {
menu.removeItem(R.id.ss_view);
}
if (isFav) {
menu.getItem(2).setIcon(R.drawable.fav_ab);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.ss_view:
Intent ssi = new Intent(this, SSActivity.class);
ssi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle b = new Bundle();
//I need to get the position of the currently active page here so that I can retrieve the //corresponding values for the title and url.
b.putString("title", threadTitle);
b.putString("url", threadUrl);
ssi.putExtras(b);
startActivity(ssi);
break;
case R.id.restart:
break;
case R.id.fav_ab:
threadUrl = new String(threadUrl.replaceAll("http://", ""));
FDBAdapter fdb = new FDBAdapter(this);
fdb.open();
if (isFav) {
Cursor c = fdb.getAllUrls();
while (c.moveToNext()) {
String id = c.getString(c.getColumnIndex("_id"));
int rowId = Integer.parseInt(id);
if(c.getString(c.getColumnIndex("url")).equals(threadUrl)) {
if (fdb.deleteUrl(rowId)) {
Log.d("THREAD", "SUCCESS");
} else {
Log.d("THREAD", "FAILED");
}
}
}
c.close();
item.setIcon(R.drawable.fav_ab_off);
isFav = false;
} else {
fdb.insertFav(threadUrl, threadTitle, ident, type, author, "thread");
item.setIcon(R.drawable.fav_ab);
isFav = true;
}
fdb.close();
default:
return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
#Override
public void onStart() {
super.onStart();
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
Heres what I mean by the currently selected page.

I believe what you are looking for is onPageChangedListener(). This method belongs to the TitlePageIndicator. Something like...
indicator.setOnPageChangedListener(new OnPageChangedListener() {
// Implement unimplemented methods...
});

you can also ask to viewpager
in java
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.getCurrentItem()
in kotlin
pager.currentItem

Related

How to fix null return from registerReceiver() in Fragment and same code was working in Activity

Problem is in the Fragment which consume the USB service and cannot register the service returning when debugging always null.
I have USB Service which is working totally fine in Activity, then I changed the code to work in fragment so i can use ViewPager ..
Now the problem that USB service is always return null and I have applied same code but it seems fragment needs other work than Activity which i still didn't catch and here's.
here's the fragment code after adding the service class and mention it in manifest.
public class RealTimeFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
TextView tvTimeStamp, tvPm25, tvPm10, tvTemp, tvHumid, tvCo2, tvTvoc, tvNoise, tvPa;
RoundCornerProgressBar pbPm25, pbPm10, pbTemp, pbHumid, pbCo2, pbTvoc, pbNoise, pbPa;
ImageView ivVent ;
public static final String TAG = "MainActivity";
private UsbService usbService;
private RealTimeFragment.MyHandler mHandler;
static String myJson = "";
static int dbCount = 0;
static ControlViewModel controlViewModel;
static View mView;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.changeBaudRate(9600);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action!=null) {
switch (action) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
}
};
public RealTimeFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static RealTimeFragment newInstance(int sectionNumber) {
RealTimeFragment fragment = new RealTimeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.realtime_layout_fragment, container, false);
tvTimeStamp = rootView.findViewById(R.id.tv_serial_output);
tvPm25 = rootView.findViewById(R.id.tv_pm25);
pbPm25 = rootView.findViewById(R.id.pb_pm25);
tvPm10 = rootView.findViewById(R.id.tv_pm10);
pbPm10 = rootView.findViewById(R.id.pb_pm10);
tvTemp = rootView.findViewById(R.id.tv_temp);
pbTemp = rootView.findViewById(R.id.pb_temp);
tvHumid = rootView.findViewById(R.id.tv_humid);
pbHumid = rootView.findViewById(R.id.pb_humid);
tvCo2 = rootView.findViewById(R.id.tv_co2);
pbCo2 = rootView.findViewById(R.id.pb_co2);
tvTvoc = rootView.findViewById(R.id.tv_tvoc);
pbTvoc = rootView.findViewById(R.id.pb_tvoc);
tvNoise = rootView.findViewById(R.id.tv_noise);
pbNoise = rootView.findViewById(R.id.pb_noise);
tvPa = rootView.findViewById(R.id.tv_pressure);
pbPa = rootView.findViewById(R.id.pb_pressure);
ivVent = rootView.findViewById(R.id.iv_vent);
mHandler = new RealTimeFragment.MyHandler(getActivity());
//assert getArguments() != null;
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
this.mView = rootView;
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
return rootView;
}
#Override
public void onResume() {
super.onResume();
// setFilters(); // Start listening notifications from UsbService
// startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
usbService.unregisterReceiver(mUsbReceiver);
usbService.unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(getContext(), service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
usbService.startService(startService);
}
Intent bindingIntent = new Intent(getContext(), service);
usbService.bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
Log.e("startService",mUsbReceiver.toString());
usbService.registerReceiver(mUsbReceiver, filter);
// LocalBroadcastManager.getInstance(usbService).registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<Activity> mActivity;
private MyHandler(Activity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String buffer = (String) msg.obj;
myJson += buffer;
if (buffer.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.SYNC_READ:
String buffer2 = (String) msg.obj;
myJson += buffer2;
if (buffer2.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
}
}
}
}
This is because you're calling:
usbService.registerReceiver(mUsbReceiver, filter);
before starting the service, which you have done in the following line:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
return rootView;
}
So, you just need to flip the code to solve the problem:
startService(UsbService.class, usbConnection, null);
setFilters();

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

java.lang.ArrayIndexOutOfBoundsException: length=2; index=2

Hi in the below code I am getting array index out of bounds exception.Here friend array it's giving two values.
For ex:
friendinfo[0]=user1,friendinfo1=user2 and with checkbox when i am selecting user1 I want to show friend.length to 2 and checked value should be 1.
this is sample screen how to add the use3 and user1 when i am clicking the create button.
GroupList.java
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
checkBoxState = new boolean[friends.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
String check=friends[position].userName;
Toast.makeText(getApplicationContext(),friends[position].userName+"checked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
GroupList.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo();
if (friends != null) {
GroupList.this.updateData(friends, null);
}
String groupname = getIntent().getStringExtra("nick");
setTitle(groupname);
ownusername = imService.getUsername();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
friendAdapter = new FriendListAdapter(this);
Button create=(Button)findViewById(R.id.create);
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
FriendInfo[] friend=FriendController.getFriendsInfo();
//checkBoxState = new CheckBox[friend.length];
/*try {
for(int i=0;i <=friend.length ;i++){
if(checkBoxState[i].isChecked()){
check[i]="1";
}
}
}catch (Exception e) {
e.printStackTrace();
}*/
String result1 = imService.CreateGroup(groupname,imService.getUsername(),friend);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stat_sample)
.setContentTitle(getText(R.string.new_friend_request_exist));
/*Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
i, 0);
mBuilder.setContentText("You have new friend request(s)");
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
}
else
{
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onPause()
{
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(GroupList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
You probably wanted to write :
if(checkBoxState[i]==isChecked)
if checkBoxState and friend arrays have the same length, checkBoxState[friend.length] is out of bounds, since the indices of an array are from 0 to length - 1.
Also note that your if condition contained an assignment operator = instead of a comparison operator ==.
Just use the index inside the for loop. Also since isChecked is already a boolean you can just assign it directly to checkBoxState
for (int i = 0; i < friend.length; i++) {
checkBoxState[i] = isChecked;
}
You are trying to access the index 2nd position in an array that has only a length of 2 (positions 0 and 1).
So please change the code as below,
if(checkBoxState[i]==isChecked)

How to show rss feed in android widget

I have a very big problem guys. I have an app which fetches and parses the RSS feed from a blog, but I don't know how to put the results into my widget.
Here is the RSSListActivity which shows the rss feed correctly in it's own activity:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
RSSItem data = itemlist.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(data.link));
startActivity(intent);
}
private void retrieveRSSFeed(String urlToRssFeed,ArrayList<RSSItem> list)
{
try
{
URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RSSParser theRssHandler = new RSSParser(list);
xmlreader.setContentHandler(theRssHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private class RetrieveRSSFeeds extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
retrieveRSSFeed("http://blog.qubiz.com/index.php/feed",itemlist);
rssadaptor = new RSSListAdaptor(RSSListActivity.this, R.layout.rssitemview,itemlist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(
RSSListActivity.this, null, "Loading RSS Feed... Please wait");
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(rssadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private class RSSListAdaptor extends ArrayAdapter<RSSItem>{
private List<RSSItem> objects = null;
public RSSListAdaptor(Context context, int textviewid, List<RSSItem> objects) {
super(context, textviewid, objects);
this.objects = objects;
}
#Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RSSItem getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view)
{
LayoutInflater vi = (LayoutInflater)RSSListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
RSSItem data = objects.get(position);
if(null != data)
{
TextView title = (TextView)view.findViewById(R.id.txtTitle);
TextView date = (TextView)view.findViewById(R.id.txtDate);
TextView description = (TextView)view.findViewById(R.id.txtDescription);
title.setText(data.title);
date.setText("on " + data.date);
String prova = android.text.Html.fromHtml(data.description).toString();
//description.setText(data.description);
description.setText(prova);
}
return view;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1,1,0,"About");
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case 1:
AlertDialog.Builder conferma_canc = new AlertDialog.Builder(this);
conferma_canc.setTitle("About");
conferma_canc.setMessage("Copyright © 2012 Qubiz. All rights reserved. Android version designed and developed by Csosz Gergo Levente, Qubiz Romania.");
conferma_canc.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = conferma_canc.create();
alert.show();
return true;
}
return false;
}
And here it is my RSS parser which also works as it should:
public class RSSParser extends DefaultHandler {
private final static String TAG_ITEM = "item";
private final static String[] xmltags = { "title", "link", "pubDate", "description" };
private RSSItem currentitem = null;
private ArrayList<RSSItem> itemarray = null;
private int currentindex = -1;
private boolean isParsing = false;
private StringBuilder builder = new StringBuilder();
public RSSParser(ArrayList<RSSItem> itemarray) {
super();
this.itemarray = itemarray;
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
if(isParsing && -1 != currentindex && null != builder)
{
builder.append(ch,start,length);
}
}
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(localName.equalsIgnoreCase(TAG_ITEM))
{
currentitem = new RSSItem();
currentindex = -1;
isParsing = true;
itemarray.add(currentitem);
}
else
{
currentindex = itemIndexFromString(localName);
builder = null;
if(-1 != currentindex)
builder = new StringBuilder();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase(TAG_ITEM))
{
isParsing = false;
}
else if(currentindex != -1)
{
if(isParsing)
{
switch(currentindex)
{
case 0: currentitem.title = builder.toString(); break;
case 1: currentitem.link = builder.toString(); break;
case 2: currentitem.date = builder.toString(); break;
case 3: currentitem.description= builder.toString(); break;
}
}
}
}
private int itemIndexFromString(String tagname){
int itemindex = -1;
for(int index= 0; index<xmltags.length; ++index)
{
if(tagname.equalsIgnoreCase(xmltags[index]))
{
itemindex = index;
break;
}
}
return itemindex;
}
}
My ExampleAppWidgetProvider.java where is a sample clock widget code which I want to replace to show my rss feed.
public class ExampleAppWidgetProvider extends AppWidgetProvider {
static DateFormat df = new SimpleDateFormat("hh:mm:ss");
private static final String LOG_TAG = "ExampleWidget";
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
Log.i("ExampleWidget", "Updating widgets " + Arrays.asList(appWidgetIds));
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
views.setTextViewText(R.id.widget1label, df.format(new Date()));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private PendingIntent createClockTickIntent(Context context) {
Intent intent = new Intent(CLOCK_WIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d(LOG_TAG, "Widget Provider enabled. Starting timer to update widget every second");
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 1);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),1000, createClockTickIntent(context));
}
#Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d(LOG_TAG, "Widget Provider disabled. Turning off timer");
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(createClockTickIntent(context));
}
public static String CLOCK_WIDGET_UPDATE = "com.eightbitcloud.example.widget.8BITCLOCK_WIDGET_UPDATE";
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d(LOG_TAG, "Received intent " + intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Log.d(LOG_TAG, "Clock update");
ComponentName thisAppWidget = new ComponentName(context.getPackageName(), getClass().getName());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
for (int appWidgetID : ids) {updateAppWidget(context, appWidgetManager, appWidgetID);
}
}
}
public static void updateAppWidget(Context context,AppWidgetManager appWidgetManager, int appWidgetId) {
String currentTime = df.format(new Date());
RemoteViews updateViews = new RemoteViews(context.getPackageName(),R.layout.widget1);
updateViews.setTextViewText(R.id.widget1label, currentTime);
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
Could any1 provide me a solution?
My aim is to: replace the widget's clock java code with my rss feed reader.
So I want to show the last rss item in the widget which is parsed by the rss parser. How can I do that?
Please provide code too, not only a few ideas, I am kinda new to android development.
Thank you for help in advance!
(Assuming you got RSS retrieval and parsing correctly)
You just have to change some text in widget:
AppWidgetManager manager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.name_of_your_widget_layout);
// set text of some view
views.setTextViewText(R.id.widget_amount_cameras, amountCameras);
// and of another view
views.setTextViewText(R.id.widget_location, locationCity);
// ... and yet another view
views.setTextViewText(R.id.locationStatus, locationStatus);
// get IDs of widgets , there could be more than one
final int[] appWidgetIds = manager.getAppWidgetIds(new ComponentName(YOurWidgetProviderClass.class.getPackage().getName(), YOurWidgetProviderClass.class.getName()));
// update all hte instances
manager.updateAppWidget(appWidgetIds, views);
You can change only some attributes of your widgets ( due to security constraints ) - See Javadoc of RemoteViews for further explanations

Categories