I'm trying to update my listview after I change the 'dataset' but it doesn't, unless I manually refresh the view or refresh the activity.
This doesn't work:
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
While this does:
handler.postDelayed(new Runnable() {
#Override
public void run() {
onCreate(null);
entriesListAdapter.notifyDataSetChanged();
}
}, 1000);
But this is absolutely not the right way to do it. Am I using notifydatasetchanged wrong?
My whole activity:
package app.wordpress;
import app.wordpress.service.FetcherService;
import someontherimports
public class EntriesListActivity extends ListActivity {
private static final int CONTEXTMENU_REFRESH_ID = 4;
private static final int CONTEXTMENU_MARKASREAD_ID = 6;
private static final int ACTIVITY_APPLICATIONPREFERENCES_ID = 1;
private static final Uri CANGELOG_URI = Uri.parse("http://wordpress.com");
private static final int CONTEXTMENU_MARKASUNREAD_ID = 7;
private static final int CONTEXTMENU_DELETE_ID = 8;
private static final int CONTEXTMENU_COPYURL = 9;
private static final int DIALOG_ABOUT = 7;
public static final String EXTRA_SHOWREAD = "show_read";
public static final String EXTRA_SHOWFEEDINFO = "show_feedinfo";
public static final String EXTRA_AUTORELOAD = "autoreload";
private static final String[] FEED_PROJECTION = {FeedData.FeedColumns.NAME,
FeedData.FeedColumns.URL,
FeedData.FeedColumns.ICON
};
private Uri uri;
private EntriesListAdapter entriesListAdapter;
private byte[] iconBytes;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
String title = null;
iconBytes = null;
Intent intent = getIntent();
long feedId = intent.getLongExtra(FeedData.FeedColumns._ID, 0);
if (feedId > 0) {
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(feedId), FEED_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
title = cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0);
iconBytes = cursor.getBlob(2);
}
cursor.close();
}
if (!MainTabActivity.POSTGINGERBREAD && iconBytes != null && iconBytes.length > 0) { // we cannot insert the icon here because it would be overwritten, but we have to reserve the icon here
if (!requestWindowFeature(Window.FEATURE_LEFT_ICON)) {
iconBytes = null;
}
}
setContentView(R.layout.entries);
uri = intent.getData();
entriesListAdapter = new EntriesListAdapter(this, uri, intent.getBooleanExtra(EXTRA_SHOWFEEDINFO, false), intent.getBooleanExtra(EXTRA_AUTORELOAD, false));
setListAdapter(entriesListAdapter);
if (title != null) {
setTitle(title);
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics());
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.setActionBarDrawable(this, new BitmapDrawable(bitmap));
} else {
setFeatureDrawable(Window.FEATURE_LEFT_ICON, new BitmapDrawable(bitmap));
}
}
}
if (RSSOverview.notificationManager != null) {
RSSOverview.notificationManager.cancel(0);
}
getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
menu.add(0, CONTEXTMENU_REFRESH_ID, Menu.NONE, R.string.contextmenu_refresh);
menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete).setIcon(android.R.drawable.ic_menu_delete);
menu.add(0, CONTEXTMENU_COPYURL, Menu.NONE, R.string.contextmenu_copyurl).setIcon(android.R.drawable.ic_menu_share);
}
});
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setTypeface(Typeface.DEFAULT);
textView.setEnabled(false);
view.findViewById(android.R.id.text2).setEnabled(false);
entriesListAdapter.neutralizeReadState();
startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(uri, id)).putExtra(EXTRA_SHOWREAD, entriesListAdapter.isShowRead()).putExtra(FeedData.FeedColumns.ICON, iconBytes));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entrylist, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.menu_group_0, entriesListAdapter.getCount() > 0);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_markasread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getReadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsRead();
break;
}
case R.id.menu_markasunread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getUnreadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsUnread();
break;
}
case R.id.menu_hideread: {
if (item.isChecked()) {
item.setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
entriesListAdapter.showRead(true);
} else {
item.setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view);
entriesListAdapter.showRead(false);
}
break;
}
case R.id.menu_deleteread: {
new Thread() { // the delete process takes some time
public void run() {
String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")";
getContentResolver().delete(uri, selection, null);
FeedData.deletePicturesOfFeed(EntriesListActivity.this, uri, selection);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
break;
}
case R.id.menu_deleteallentries: {
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.contextmenu_deleteallentries);
builder.setMessage(R.string.question_areyousure);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
break;
}
case CONTEXTMENU_MARKASREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getReadContentValues(), null, null);
entriesListAdapter.markAsRead(id);
break;
}
case CONTEXTMENU_MARKASUNREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getUnreadContentValues(), null, null);
entriesListAdapter.markAsUnread(id);
break;
}
case CONTEXTMENU_DELETE_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null);
FeedData.deletePicturesOfEntry(Long.toString(id));
entriesListAdapter.getCursor().requery(); // he have no other choice
break;
}
case CONTEXTMENU_COPYURL: {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView.getTag().toString());
break;
}
case R.id.menu_settings: {
startActivityForResult(new Intent(this, ApplicationPreferencesActivity.class), ACTIVITY_APPLICATIONPREFERENCES_ID);
break;
}
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
}
}
return true;
}
#Override
protected void onResume()
{
super.onResume();
setProgressBarIndeterminateVisibility(isCurrentlyRefreshing());
registerReceiver(refreshReceiver, new IntentFilter("app.wordpress.REFRESH"));
}
#Override
protected void onPause()
{
unregisterReceiver(refreshReceiver);
super.onPause();
}
private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setProgressBarIndeterminateVisibility(true);
}
};
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case DIALOG_ABOUT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.menu_about);
MainTabActivity.INSTANCE.setupLicenseText(builder);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(R.string.changelog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, CANGELOG_URI));
}
});
return builder.create();
}
default: dialog = null;
}
return dialog;
}
private boolean isCurrentlyRefreshing()
{
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)) {
if (FetcherService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Are you referring to this block of code in your Activity?
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
If so, the problem is likely that the call to runOnUiThread() is not actually inside of the Thread you created, it's called on the main thread.
The way this code is structured, upon selecting refresh, the background thread is created to fire a broadcast Intent (not necessary, BTW, because that is also an asynchronous process...it returns immediately) and then notifyDataSetChanged() is immediately run after that (because runOnUiThread() when called from the main thread just executes the Runnable right away).
So you are sending a broadcast and updating the adapter at basically the same time...not much time for anything to have actually changed in that period. If you were expecting sendBroadcast() to block and return after some receiver had processed it, this is not the case.
In you contentProvider, you should call contentResolver.notifyChange to notify the adapter that there have been a change to the data provided by the contentResolver, this will update the listView for you.
Related
I am creating this application which has three tabs. Tab1 is used to handle bluetooth incoming and outgoing connections. The major problem comes here is once i click the connect button the connection is created but when i switch tabs and then jump back to tab1 everything is lost as the tab is reinitialized. I want to stop this from happening. Please suggest me the correction in my code.
Here is the MainActivity.java file
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
StringBuilder recDataString = new StringBuilder();
int handlerState = 0;
private ViewPager viewPager;
int initialize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Manual"));
tabLayout.setSelectedTabIndicatorColor(Color.BLACK);
tabLayout.addTab(tabLayout.newTab().setText("Status"));
tabLayout.addTab(tabLayout.newTab().setText("Database"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager)findViewById(R.id.pager);
Pager adapter = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setOnTabSelectedListener(this);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("BS");
Log.d("********", "ID = " + id);
/*if (id.equalsIgnoreCase("F")) {
sendToConnectedThread(id);
}*/
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.nitesh.finaltab.DATA_BROADCAST");
getApplicationContext().registerReceiver(broadcastReceiver,filter);
}
public int getInitialize(){
return initialize;
}
public void setInitialize(int m){
this.initialize = m;
}
#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 void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Here is the Pager.java file
public class Pager extends FragmentStatePagerAdapter {
int tabcount;
public Pager(FragmentManager fm, int tabcount){
super(fm);
this.tabcount = tabcount;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount(){return tabcount;}
}
And here is the Tab1.java file
public class Tab1 extends Fragment {
SQLiteDatabase alexadb,activitydb;
MainActivity mainActivity= new MainActivity();
StringBuilder recDataString = new StringBuilder();
String address = "98:D3:32:20:5A:57";
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int handlerState = 0;
public boolean isBtConnected = false;
ProgressDialog progressDialog;
int initialize = 0;
Handler bluetoothIn;
BluetoothAdapter myBluetooth;
BluetoothSocket bluetoothSocket;
ConnectedThread connectedThread ;
Button connect,forward,reverse,left,right,stop;
int speed;
String datatoSend;
private final long REPEAT_DELAY = 50;
boolean autoIncreament,autoDecreament;
View view;
private Handler repeatUpdateHandler = new Handler();
private Handler senddataUpdatehandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDatabase();
view = inflater.inflate(R.layout.tab1, container, false);
forward = (Button) view.findViewById(R.id.bforward);
reverse = (Button) view.findViewById(R.id.breverse);
left = (Button) view.findViewById(R.id.bleft);
stop = (Button) view.findViewById(R.id.bstop);
connect = (Button)view.findViewById(R.id.buttonConnect);
right = (Button) view.findViewById(R.id.bright);
Toast.makeText(getContext(), "Tab1 Initiated", Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Ready to connect?");
handler();
class RepetitiveUpdater implements Runnable {
#Override
public void run() {
if (autoIncreament) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecreament) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Process Initiated", Toast.LENGTH_SHORT).show();
new CheckBT().execute();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// bluetoothConnect.sendData("R");
Log.d("Right", "Button is clicked");
sendData("R");
insertIntoActivityDB("Right Button is clicked");
}
});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("L");
insertIntoActivityDB("Left Button is clicked");
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("B");
insertIntoActivityDB("Reverse Button is clicked");
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autoDecreament = false;
autoIncreament = false;
sendData("S");
insertIntoActivityDB("Stop Button is clicked");
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
sendData("F");
insertIntoActivityDB("Forward Button is clicked");
}
});
forward.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
autoIncreament = true;
autoDecreament = false;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
forward.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && autoIncreament) {
autoIncreament = false;
autoDecreament = true;
sendData("D");
repeatUpdateHandler.post(new RepetitiveUpdater());
}
return false;
}
});
return view;
}
public void handler() {
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endofLineIndex = recDataString.indexOf("~");
if (endofLineIndex > 0) {
// String dataInPrint = recDataString.substring(0,endofLineIndex);
String data = recDataString.substring(1, endofLineIndex);
Log.d("Received Text", "" + data);
String first = recDataString.substring(0, 1);
Log.d("First letter ", "Hello" + first);
if (first.equalsIgnoreCase("P")) {
insertIntoAlexaDB(data);
}
if (first.equalsIgnoreCase("V")) {
insertIntoAlexaDB(data);
} else {
}
recDataString.delete(0, recDataString.length());
// dataInPrint = " ";
data = "";
first = " ";
}
}
}
};
}
public void increment(){
speed++;
sendData("F");
Log.d("Increasing Speed"," "+speed);
}
public void decrement() {
if (speed > 0) {
speed--;
sendData("D");
Log.d("Decreasing Speed", " " + speed);
}
}
public class CheckBT extends AsyncTask<Void, Void, Void>//UI Thread
{
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getContext(), "Connecting you", "From Alexa");
Toast.makeText(getContext(),"Conneting",Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
if (bluetoothSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = myBluetooth.getRemoteDevice(address);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID); //Create RFCOMM connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
Toast.makeText(getContext(), "HC-05 didn't respond", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getContext(), "Connection Failed. Try Again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
isBtConnected = true;
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
}
progressDialog.dismiss();
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the thread
public ConnectedThread(BluetoothSocket bluetoothSocket){
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
//create I/O streams for connection
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
}catch (IOException
e){}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public boolean getBluetoothStatus() {
Toast.makeText(getContext(),"Bluetooth Status from thread"+isBtConnected,Toast.LENGTH_SHORT).show();
return isBtConnected;
}
public void run(){
byte[] buffer = new byte[256];
int bytes;
//keep looping ot listen for received messages
while(true){
try{
Log.d("Running"," Connected_Thread");
isBtConnected = true;
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer,0,bytes);
//Send the obtained bytes to the UIActivity via handler
bluetoothIn.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();
}catch (IOException e){
break;
}
}
}
}
public void sendData(String data) {
try {
bluetoothSocket.getOutputStream().write(data.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creation of DATABASE**/
public void createDatabase(){
alexadb = getContext().openOrCreateDatabase("AlexaDB", Context.MODE_PRIVATE,null);
activitydb= getContext().openOrCreateDatabase("ActivityDB",Context.MODE_PRIVATE,null);
alexadb.execSQL("CREATE TABLE IF NOT EXISTS alexa(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
activitydb.execSQL("CREATE TABLE IF NOT EXISTS activity(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
}
public boolean insertIntoAlexaDB( String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO alexa(data)VALUES('" + data + "');";
alexadb.execSQL(query);
return true;
}
}
public boolean insertIntoActivityDB(String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO activity(data)VALUES('" + data + "');";
activitydb.execSQL(query);
return true;
}
}
}
Is this happening only when you select the last tab? Take a look at the offscreen page limit parameter: basically you can set the number of pages to retain in memory when you scroll the ViewPager. In your case, an offscreen page limit of 2 should be enough to always keep all the pages in memory.
I have created app that detects otg cable,when otg cable is plugged in or out popup message appears that says otg connected or otg disconnected.How to make that popup appears when button on toolbar is clicked,popup message should only appear in action bar when otg cable is not connected,when it's connected it's should be hidden?
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
public static final String IS_CONNECTED_KEY = "isConnectedValue";
public void startOtgService()
{
startService(new Intent(MainActivity.this, OtgService.class));
}
public void stopOtgService()
{
stopService(new Intent(MainActivity.this, OtgService.class));
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button_autootg);
button.setTag(0);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
button.setText("");
final int status = (Integer) view.getTag();
switch (status)
{
case 0:
startOtgService();
button.setText("OTG Service Enabled");
button.setBackgroundColor(Color.GREEN);
view.setTag(1);
break;
case 1:
stopOtgService();
button.setText("OTG Service Disabled");
button.setBackgroundColor(Color.RED);
view.setTag(0);
break;
}
}
});
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
#Override
protected void onNewIntent(Intent intent)
{
if (intent.getExtras() == null)
{
super.onNewIntent(intent);
Log.e("###", "No extras");
return;
}
if (intent.hasExtra(IS_CONNECTED_KEY))
{
Log.e("###", "Displaying dialog");
boolean isConnected = intent.getExtras().getBoolean(IS_CONNECTED_KEY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Otg state changed");
if (isConnected)
alertDialog.setMessage("OTG connected");
else
alertDialog.setMessage("OTG disconnected");
alertDialog.show();
}
else
{
Log.e("###", "Does not contain key");
super.onNewIntent(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_cable)
{
}
return super.onOptionsItemSelected(item);
}
}
public class OtgService extends Service
{
private boolean mOtgConnected = false;
private Handler mHandler;
Timer taskTimer = new Timer();
TimerTask task = new TimerTask()
{
private int last_Length = -1;
#Override
public void run()
{
Context context = OtgService.this.getBaseContext();
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
int conn_length = contents.length;
if(conn_length ==last_Length)
{
return;
}
else
{
last_Length = conn_length;
}
if(conn_length == 0)
{
mOtgConnected = false;
mHandler.post(flagChangedTask);
}
else if (conn_length > 0) //Might get a -1
{
mOtgConnected = true;
mHandler.post(flagChangedTask);
}
if(conn_length == 0)
{
displayDialog(false);
}
else if (conn_length > 0) //Might get a -1
{
displayDialog(true);
}
}
};
//Will post this to the main thread
Runnable flagChangedTask = new Runnable()
{
#Override
public void run()
{
if (mOtgConnected)
Toast.makeText(OtgService.this,"otg connected",Toast.LENGTH_SHORT).show();
else
Toast.makeText(OtgService.this,"otg not connected",Toast.LENGTH_SHORT).show();
}
};
public OtgService()
{
}
public void displayDialog(boolean isConnected)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(MainActivity.IS_CONNECTED_KEY, isConnected);
startActivity(intent);
}
private void onStartCompat(Intent intent)
{
Log.e("###", "Starting service!");
if (mHandler == null)
mHandler = new Handler(getMainLooper());
taskTimer.scheduleAtFixedRate(task, 0, 1000);
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId)
{
onStartCompat(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
onStartCompat(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy()
{
//task.cancel();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
Add the following code in your code. When cable state changed, call cableStateWasChanged(boolean isConnected). This will show the popup button in your toolbar. When the button is clicked, a popup is shown and the button disappears. You can change the popup title and message depending on the cable state as you want it to be.
private boolean isCableConnected = false;
private boolean cableStateChanged = false;
private boolean popupWasShown = false;
#Override
public boolean onPrepareOptionsMenu(Menu menu){
MenuItem item = menu.findItem(R.id.action_popup);
if (cableStateChanged && !popupWasShown) {
item.setVisible(true);
cableStateChanged = false;
} else if (popupWasShown) {
item.setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == ...) {
...
} else if (id == R.id.action_popup) {
popupWasShown = true;
invalidateOptionsMenu();
// You can change the popup title, message and buttons here
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(isCableConnected ? "Cable was connected" : "Cable was disconnected");
builder.setMessage("foo bar");
builder.setPositiveButton("OK", null);
builder.setNegativeButton(null, null);
builder.create().show();
}
return super.onOptionsItemSelected(item);
}
private void cableStateWasChanged(boolean isConnected) {
isCableConnected = isConnected;
cableStateChanged = true;
popupShown = false;
invalidateOptionsMenu();
}
Also I suggest you to use Handler instead of TimerTask, see this post
When my first to get the data from the first tab of fragment,it was something wrong.And through the web page to open it ,these data is normal.
public class OnlineAllInsuranceFragment extends Fragment implements OnListViewListener {
private ScrollListView MainView;
private BasicAdapter2 Adapter;
private Integer Step=10;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
private DataTable dTable;
public static String SelectCode="";
private static final int OVER = 1;
private String polnum;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_online_insurance,container,false);
handler2 = new Handler();
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
Looper.loop();
}
}).start();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
}
private void SetList(){
Start=0;
End=3;
this.dTable = new DataTable(getActivity(),"newcontract");
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(dTable.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.dTable.GetList(),R.layout.userlistitem4);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter2(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,
R.id.listitem_main1,R.id.contractitem_label_companyImage,R.id.contractitem_label_payImage },
new BasicAdapter2.ListAdapterListener() {
#Override
public void onClickAtOKButton(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
switch (v.getId()) {
case R.id.listitem_button_pay:
polnum = dTable.GetValue((Integer)v.getTag(), 3).toString();
String numPol = dTable.GetValue((Integer)v.getTag(), 2).toString();//是“保单号”还是“投保单号”
if (numPol.contains("aa")) {
Intent intent = new Intent();
intent.setClass(getActivity(),PolicyInformationActivity.class);
intent.putExtra("polnum", polnum);
startActivity(intent);
} else if (numPol.contains("bb")) {
toastDialog();
}
break;
case R.id.listitem_button_look:
Toast.makeText(getActivity(),"...", Toast.LENGTH_SHORT).show();
LogUtil.e("company+status", company+"=="+status);
break;
case R.id.listitem_main1:
break;
}
}
},
new BasicAdapter2.VisibleAdapterListener() {
#Override
public int onSetVisible(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
LogUtil.e("status","=="+status);
int drawId;
switch (v.getId()) {
case R.id.contractitem_label_companyImage:
if ( company.contains("cc") ) {
drawId = R.drawable.taikang2x;
return drawId;
} else if (company.contains("dd") ) {
drawId = R.drawable.youban2x;
return drawId;
}
break;
case R.id.contractitem_label_payImage:
if ( status.equals("ee") ) {
drawId = R.drawable.security2x;
return drawId;
} else if (status.equals("ff")) {
drawId = R.drawable.nopay2x;
return drawId;
} else if ( status.equals("gg")) {
drawId = R.drawable.invalid2x;
return drawId;
}
break;
case R.id.listitem_button_pay:
if (company.contains("hh") && status.equals("ii")) {
return 0;
} else if (company.contains("jj") || status.equals("kk")) {
return 4;
}
break;
}
return 99;
}
});
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("just");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
private void toastDialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
builder.setTitle("xx");
builder.setMessage("yy");
builder.setNegativeButton("vv", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("ww", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
startActivity(new Intent(getActivity(),HomeActivity.class));
send();
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.setCancelable(false);
noticeDialog.setCanceledOnTouchOutside(false);
noticeDialog.show();
}
private void send() {
}
}
And when I keep away from this Fragment then comeback,the data become normal,too.The data is not normal just when my first in the Fragment.
Hi in the below code After clicking login button with internet working fine.suppose there is no internet connection it's not working I want to show diaglog there is no internet connection.
Can any one help me from this issue.
Login1.java
public class Login1 extends Activity {
protected static final int NOT_CONNECTED_TO_SERVICE = 0;
protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
public static final String AUTHENTICATION_FAILED = "0";
public static final String FRIEND_LIST = "FRIEND_LIST";
protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
protected static final int NOT_CONNECTED_TO_NETWORK = 3;
private EditText usernameText;
private EditText passwordText;
private Button cancelButton;
private IAppManager imService;
public static final int SIGN_UP_ID = Menu.FIRST;
public static final int EXIT_APP_ID = Menu.FIRST + 1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
if (imService.isUserAuthenticated() == true)
{
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Login1.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
Boolean isInternetPresent = false;
ConnectionDetector cd;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Login1.this, IMService.class));
setContentView(R.layout.login_screen);
setTitle("Login");
Button loginButton = (Button) findViewById(R.id.login);
cancelButton = (Button) findViewById(R.id.cancel_login);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener(){
#SuppressWarnings("deprecation")
public void onClick(View arg0)
{
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
if (imService == null) {
Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();
return;
}
else if (imService.isNetworkConnected() == false)
{
Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
showDialog(NOT_CONNECTED_TO_NETWORK);
}
else if (usernameText.length() > 0 &&
passwordText.length() > 0)
{
Thread loginThread = new Thread(){
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(usernameText.getText().toString(), passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED))
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();
}
});
}
else {
handler.post(new Runnable(){
public void run() {
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
});
}
}
};
loginThread.start();
}
else {
Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password, Toast.LENGTH_LONG).show();
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
imService.exit();
finish();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
int message = -1;
switch (id)
{
case NOT_CONNECTED_TO_SERVICE:
message = R.string.not_connected_to_service;
break;
case FILL_BOTH_USERNAME_AND_PASSWORD:
message = R.string.fill_both_username_and_password;
break;
case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
message = R.string.make_sure_username_and_password_correct;
break;
case NOT_CONNECTED_TO_NETWORK:
message = R.string.not_connected_to_network;
break;
default:
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Login1.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.create();
}
}
#Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
bindService(new Intent(Login1.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId())
{
case SIGN_UP_ID:
Intent i = new Intent(Login1.this, SignUp.class);
startActivity(i);
return true;
case EXIT_APP_ID:
cancelButton.performClick();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login1.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Add this function
public static boolean CheckInternet(Context context) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifi.isConnected() || mobile.isConnected();
}
This function check the wifi or the mobile network if available and return true if yes false if no
and replace this:
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
By this code:
if (!CheckInternet(this)) {
new AlertDialog.Builder(this)
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
return;
}
as you said :
I want to show diaglog there is no internet connection.
Use this function :
public static boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
and in your code check internet connection :
if (!isNetworkAvailable()) {
// show your dialog here
}
I have a ProgressDialog, and I want to do something when the dialog dissappears (but I do not want put my action after the progressdialog.dismiss).
Is it possible to:
----> if No ---> Do something
Check if dialog is showing
----> if Yes
/|\ |
| \|/
--------------------- Wait
Don't think to difficult, I just want to perform an action, but only if there is no dialog, and if there is one, to perform the action when the dialog is done.
Thank you!
EDIT: My activity:
import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {
private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;
private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;
public ScroidWallpaperGallery() {
super();
if (!DependencyInjector.isInitialized()) {
DependencyInjector.init(this);
}
this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);
this.preloadedList = new ArrayList<Integer>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.initGallery();
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(this.getString(R.string.loadingText));
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
else {
SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
if (this.wallpaperGalleryAdapter != null) {
this.updateGalleryAdapter();
return;
}
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
new FillGalleryTask(progressDialog, this).start();
}
private void updateGalleryAdapter() {
this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}
private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setAdapter(this.wallpaperGalleryAdapter);
}
private void initGallery() {
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);
showPreviewActivity(wallpaper);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);
new Thread(new Runnable() {
#Override
public void run() {
preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedWallpaper = null;
}
});
this.registerForContextMenu(gallery);
}
private void showPreviewActivity(Wallpaper wallpaper) {
WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}
private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
if (this.preloadedList.contains(i)) {
continue;
}
try {
this.wallpaperManager.getThumbImage(wallpapers[i]);
this.preloadedList.add(i);
}
catch (ClientProtocolException ex) {
// nothing to do - image will be loaded on select
}
catch (IOException ex) {
// nothing to do - image will be loaded on select
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (this.selectedWallpaper == null
|| !(v instanceof Gallery)) {
return;
}
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.gallery_context_menu, menu);
if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
}
else {
menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (this.selectedWallpaper == null) {
return false;
}
switch (item.getItemId()) {
case R.id.galleryAddFavouriteMenuItem:
this.favouriteDAO.add(this.selectedWallpaper.getId());
return true;
case R.id.galleryRemoveFavouriteMenuItem:
this.favouriteDAO.remove(this.selectedWallpaper.getId());
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutMenuItem:
this.showDialog(DIALOG_ABOUT);
return true;
case R.id.settingsMenuItem:
this.startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.recommendMenuItem:
this.recommendWallpaper();
return true;
case R.id.favouritesMenuItem:
FavouriteListActivity.showFavouriteListActivity(this);
return true;
case R.id.closeMenuItem:
this.finish();
return true;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ABOUT:
return new AboutDialog(this);
default:
return null;
}
}
private void recommendWallpaper() {
if (this.selectedWallpaper == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
this.startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_CONTACT:
this.onPickContactActivityResult(resultCode, data);
break;
}
}
private void onPickContactActivityResult(int resultCode, Intent data) {
if (resultCode == 0) {
return;
}
Communication[] communications = this.communicationDAO.getCommunications(data.getData());
if (communications.length < 1) {
AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);
return;
}
CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
#Override
public void onCommunicationChosen(Communication communication) {
handleOnCommunicationChosen(communication);
}
});
dialog.show();
}
private void handleOnCommunicationChosen(Communication communication) {
Wallpaper wallpaper = this.selectedWallpaper;
if (communication.getType().equals(Communication.Type.Email)) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern),
wallpaper.getWallpaperUrl()));
intent.setType("message/rfc822");
this.startActivity(intent);
}
else if (communication.getType().equals(Communication.Type.Mobile)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", communication.getValue());
intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern),
wallpaper.getWallpaperUrl()));
intent.setType("vnd.android-dir/mms-sms");
this.startActivity(intent);
}
}
private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {
private final Context context;
public FillGalleryTask(Dialog progressDialog, Context context) {
super(progressDialog);
this.context = context;
}
#Override
public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
updateGalleryAdapter(result);
}
#Override
public void handleUncaughtException(Throwable ex) {
if (ex instanceof WallpaperListReceivingException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
ex.getMessage(),
new ShutDownAlertDialogOnClickListener());
}
else if (ex instanceof IOException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
R.string.downloadException,
new ShutDownAlertDialogOnClickListener());
}
else {
throw new RuntimeException(ex);
}
}
#Override
public Wallpaper[] onRun() throws Exception {
// retrieving available wallpapers from server
wallpaperManager.loadAvailableWallpapers(getBaseContext());
Wallpaper[] wallpapers = wallpaperManager.getWallpapers();
// preloading first 3 thumbs
preloadThumbs(wallpapers, 0, 3);
return wallpapers;
}
}
private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
}
Try this,
private void doSomethingWhenProgressNotShown() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomethingWhenProgressNotShown();
}
}, 500);
}
//isnt running- do something here
}
I think you can use this code:
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
}
//isnt running
Or you can set listeners:
mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);