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
}
Related
How to show message in showDialog();
I want when freshDownloadView is finished show showDialog.
My code is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
private FreshDownloadView freshDownloadView;
private Button btDownloaded;
private TextView btReset;
private TextView btDownloadError;
private final int FLAG_SHOW_OK = 10;
private final int FLAG_SHOW_ERROR = 11;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int progress = (int) msg.obj;
freshDownloadView.upDateProgress(progress);
switch (msg.what) {
case FLAG_SHOW_OK:
break;
case FLAG_SHOW_ERROR:
freshDownloadView.showDownloadError();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
freshDownloadView = (FreshDownloadView) findViewById(R.id.pitt);
btDownloaded = (Button) findViewById(R.id.bt_downloaded);
btReset = (Button) findViewById(R.id.bt_reset);
btDownloadError = (Button) findViewById(R.id.bt_download_error);
btDownloaded.setOnClickListener(this);
btReset.setOnClickListener(this);
btDownloadError.setOnClickListener(this);
}
this is button freshDownload
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_downloaded:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
message.obj = i;
handler.sendMessage(message);
showDialog();
}
}
}).start();
break;
case R.id.bt_reset:
freshDownloadView.reset();
break;
case R.id.bt_download_error:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 30; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
if (i == 30) {
message.what = FLAG_SHOW_ERROR;
}
message.obj = i;
handler.sendMessage(message);
}
}
}).start();
break;
}
}
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setMessage(R.string.download_app)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
protected void onPause() {
// unregisterReceiver(receiver);
super.onPause();
}
protected void onResume() {
// registerReceiver(receiver, new IntentFilter(
// WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
}
I suggest you use AsyncTask for this. You can initiate the download in the doInBackground method and show the alert dialog (as needed) in the onPostExecute method. This will also free you from using Thread.sleep(100) which isn't a good practice on Android.
However, if you still prefer to use the FreshDownloadView please update your question with the code for FreshDownloadView and we can suggest something.
My app needs internet to work so i'm trying to check the internet connection work or not i want when internet is turn off app show the user dialog with TRY AGAIN button when user click TRY AGAIN Button and interent connection still doesn't work Show Dialog (internet doesn't work try again )
check internet connection method :
public Boolean CheckInternetConnection(){
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
return true;
}
else
return false;
}
inside onCreate
protected void onCreate(){
......
......
if(CheckInternetConnection()){
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.info)
.setTitle("Internet Connection !")
.setMessage("No Internet Connection")
.setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(CheckInternetConnection()){
//TRY AGAIN and REOPEN DIALOG
}
}
});
builder.setCancelable(false);
AlertDialog about = builder.create();
about.show();
TextView messageText = (TextView) about.findViewById(android.R.id.message);
assert messageText != null;
messageText.setGravity(Gravity.CENTER);
Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(Color.BLACK);
}
Create showDialog() separate method and call it whenever you need to show the dialog again.
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
if (isNetworkConnected()) {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
} else {
showDialog();
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("No Internet Connection");
builder.setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isNetworkConnected()) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
} else {
showDialog();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
if you get the connection fail and then show dialog like "your connection fail" try this code below .
mainactivity
public class MyActivity implements NetworkStateReceiverListener {
private NetworkStateReceiver networkStateReceiver;
}
oncreate
public void onCreate(Bundle savedInstanceState) {
/* ... */
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
mainactivity
#Override
public void networkAvailable() {
// internet connection success
}
#Override
public void networkUnavailable() {
//REOPEN DIALOG
}
the receiver
public class NetworkStateReceiver extends BroadcastReceiver {
protected List<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new ArrayList<NetworkStateReceiverListener>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
private void notifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null)
return;
if(connected == true)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
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
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.