Hello everyone i hope you can help.
I've built an RSS reader which populates a ListView. I want to check the user has network access on app start up, if there is no network then the user should see the setEmptyView View and a toast.
In onCreate I've set the list adapter with an empty list so I'm expecting to see the empty view. Then i query the network state and if no network i create a toast. BUT I never see the empty view on start-up and i never see the toast when i don't have a network. Whats going on?
public class XMLActivity extends ListActivity {
private List<JSONObject> jobs = new ArrayList<JSONObject>();
private RssListAdapter adapter;
private ListView lv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//SET LAYOUT WITH EMPTY LIST VIEW
setContentView(R.layout.main);
View empty = findViewById(R.id.empty);
lv = getListView(); //get view layout
lv.setEmptyView(empty); //set empty view
adapter = new RssListAdapter(this,jobs); //jobs is empty array list
setListAdapter(adapter);
//CHECK FOR NETWORK AND DISPLAY TOAST
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
// START RSS READER HANDLER
try {
jobs = RssReader.getLatestRssFeed();
} catch (Exception e) {
}
//REFRESH ADAPTER FOR LISTVIEW
adapter.clear();
for(JSONObject job :jobs){
adapter.add(job);
}
adapter.notifyDataSetChanged();
lv.setClickable(true);
Why can't i see the empty view or toast, this problem only happens for the onCreate routine. Later toasts and empty views are displayed fine on menu item select so it seems to be a problem specific to the onCreate sequence.
try Toast.makeToast(this, "msg to user", Toast.TOAST_MSG_SHORT).show(); i'm sure i have a typo in there as i don't have my devopment machine up and running (yet).
use :
Toast.makeText(XMLActivity.this , "No Network", Toast.LENGTH_LONG).show();
if (!network){
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
TextView txt1 = new TextView(this);
txt1.setText("No Network");
toast.setView(txt1);
toast.show();
}
else ...
Try this..,,.
You have one condition not covered - what happens if network == true?
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(XMLActivity.this, "Network Access!", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
Related
I have an activity that list authorized users, and I'm using getIntent() in my activity's onCreate() method to check if the activity should display a pre-filled add user dialog when it loads. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_auth_manager);
try{ //check if the activity was launched with a prefill intent
Intent intent = getIntent();
int id = (intent.getIntExtra("notification_id",0));
NotificationUtils notificationUtils = new NotificationUtils();
notificationUtils.hideNotification(this,id);
if (intent.getBooleanExtra("isPrefill",false)){
String preFill = intent.getStringExtra("sender");
showAddUserDialog(preFill);
}
}catch (Exception ignore){} //exception swallowed means no dialog
refreshList(); //loads the list of users into the main listview of the activity
}
My problem is that the call to refreshList() is not resulting in the list being refreshed. I tried putting it before the try block as well, and either way it won't work. I tested with the try block commented out though, and that does work, but then I lose the functionality.
Here is the code of the refreshList() method, in case it's necessary:
private void refreshList(){
SharedPreferences sharedPrefs = getSharedPreferences("users",0);
LinearLayout ll = findViewById(R.id.ll);
ll.removeAllViews();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
for (String sender : sharedPrefs.getAll().keySet()) {
CheckBox checkBox = new CheckBox(this);
checkBox.setText(getContactDisplayName(sender));
checkBox.setTag(sender);
try{
checkBox.setChecked(sharedPrefs.getBoolean(sender,false));
}catch (Exception e){
checkBox.setChecked(false);
}
checkBox.setLayoutParams(layoutParams);
checkBox.setOnClickListener(v -> {
try {
sharedPrefs.edit().putBoolean(sender, checkBox.isChecked()).apply();
}catch (Exception e){
Toast.makeText(this, "Preference not updated.\n"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
checkBox.setOnLongClickListener(v -> {
showPopupMenu(v);
return false;
});
ll.addView(checkBox);
}
}
Why does the try block prevent the UI from refreshing, and how can I acheive the functionality I am looking for?
If you intend to run the refreshList method regardless if there is an exception or not you can try using the finally block which would run the code regardless of the exception.
I am trying to make an app to turn on mobile data on click. However, it requires to detect if mobile data is already on. If it is already on, data1.png is displayed else data0.png. However, for some reason it is not changing. TEST 2 is running though. (wdata is Image Button) This is the code:
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
Toast.makeText(MainActivity.this, ""+mobEnabled, Toast.LENGTH_SHORT).show();
IF MOBILE DATA IS ENABLED, IT RETURNS TRUE.
if(mobEnabled){
wdata1=getResources().getDrawable(R.drawable.data1);
Toast.makeText(MainActivity.this, ":Test 1:"+mobEnabled, Toast.LENGTH_SHORT).show(); //RUNS
wdata.setImageDrawable(wdata1);// DOESN'T SET
}else{
wdata1 =
getResources().getDrawable(R.drawable.data0);
Toast.makeText(MainActivity.this, ":Test 2:"+mobEnabled, Toast.LENGTH_SHORT).show();
wdata.setImageDrawable(wdata1);
}
I have used the Drawable wdata1 in other areas:
wdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mobileDataEnabled(getApplicationContext())){
setMobileDataEnabled(getApplicationContext(), false);
wdata1 =
getResources().getDrawable(R.drawable.data0);
amobileDataEnabled = false;
}else{
setMobileDataEnabled(getApplicationContext(),true);
wdata1 =
getResources().getDrawable(R.drawable.data1);
amobileDataEnabled = true;
}
wdata.setImageDrawable(wdata1);
}
});
And in the onResume() method:
if( amobileDataEnabled){
wdata1 =
getResources().getDrawable(R.drawable.data1);
wdata.setImageDrawable(wdata1);
}else {
wdata1 =
getResources().getDrawable(R.drawable.data0);
wdata.setImageDrawable(wdata1);
}
After setting a drawable to something else, try calling wdata.invalidateDrawable(wdata1); right afterwards to indicate it needs to be refreshed.
I have an Activity that loads all vouchers on the server to customer's phone. In that Activity, I have 2 buttons. The first button will get all vouchers that bought by the customer. The second will get the list of all available vouchers that customer can buy.
Now, the problem is, I need only onListItemClick for the list of available vouchers (when they click on those vouchers, they have option to buy). I use ListView as ListActivity. When I set onListItemClick, the event apply for bought vouchers as well.
How can I somehow deactivate onListItemClick event when customers view their own vouchers and activate it when customers choosing voucher to buy?
This is my code of the two buttons:
public void btn_Own(View v){
if(!isConnected){
Toast toast = Toast.makeText(Voucher.this, "Cannot connect to internet", Toast.LENGTH_LONG);
toast.show();
return;
//finish();
}
if(email.equals("")){
Toast toast = Toast.makeText(Voucher.this, "Please log in to see your voucher!", Toast.LENGTH_LONG);
toast.show();
}else{
url = "http://wswob.somee.com/wobservice.svc/checkOwnVoucher/" + email + "/";
new checkingTask().execute();
}
}
public void btn_Shop(View v){
if(!isConnected){
Toast toast = Toast.makeText(Voucher.this, "Cannot connect to internet", Toast.LENGTH_LONG);
toast.show();
return;
//finish();
}
url = "http://wswob.somee.com/wobservice.svc/showVoucher";
new MyTask().execute();
}
I'm new to Android, so I just came to know that I have to use custom adapter to do so (as far as I know). But I wonder how can I do that while I'm using asynctask and pass different parameters when I need that do execute different tasks from web service.
This is how I get the list after calling web service:
protected void onPostExecute(Void result){
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
Voucher.this, voucherList,
R.layout.voucher_list, new String[]{"detail","price"},
new int[]{R.id.detail, R.id.price});
setListAdapter(null);
setListAdapter(adapter);
}
You should be able to use setEnabled to true or false to control when the user can actually click the link or button.
You should use the button click events of activity,you have two button,onclick of frist but just make the listview Itemclicklistener disable after loading all vocher from server and on click of second button which loads available vochers only make your listviewItem clickable.
I'm having trouble closing my toast message that I'm creating in the activity BarcodeActivity after I pass over the intent to another class, UPCHandler. Since I can't pass toasts through intents, I haven't been able to find a way to manipulate the toast message from the UPCHandler intent.
BarcodeActivity:
public void didScanBarcode(String barcode, String symbology)
{
// Remove non-relevant characters that might be displayed as rectangles
// on some devices. Be aware that you normally do not need to do this.
// Only special GS1 code formats contain such characters.
String cleanedBarcode = "";
for (int i = 0 ; i < barcode.length(); i++)
{
if (barcode.charAt(i) > 30)
{
cleanedBarcode += barcode.charAt(i);
}
}
try
{
//stops scanner
mBarcodePicker.stopScanning();
Log.e("CleanedUPC", cleanedBarcode);
/* Toast Setup */
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Fetching your results...");
Toast toast = BarcodeActivity.toast;
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
#Override
public String dataRetreived()
{/*
Intent i = new Intent(getApplicationContext(), UPCHandler.class);
Bundle bundle = new Bundle();
bundle.put("value", inputTransacVal.getText());
i.putExtras(bundle);
startActivity(i);*/
ItemsDto idt = hand.getFirstUpc();
if (idt == null)
{
Log.e("BarcodeActivity:didScanBarcode", "UPC is NULL");
toast.cancel();
}
else
{
Intent intn_display = new Intent("com.ahold.scan.DISPLAYSCREEN");
Intent intn_warning = new Intent("com.ahold.scan.WARNINGSCREEN");
ImageLoader imgLoad = new ImageLoader(idt.getImageUrl(), context, idt)
*/
}
return null;
}
});
}
catch(Exception e)
{
//throws an error message to logcat if it catches one
Log.e("IntentStartError", e.toString());
}
}
There are two things you can try to do:
Close the toast before switching activities, pass an indication in your intent that the toast needs to be reshown, and show it in the new activity.
Pass the toast. Put it in a static variable somewhere, and in your new activity cancel it if it's not null. Keep in mind that it might be null, because Android can kill your process and start it again between activities.
When my submit button is clicked, it calls a method which checks if a certain EditText is empty and displays a toast message as an error message accordingly. However, if I rapidly tap on submit, it "queues" a lot of toast messages. How can I prevent this?
Here's my method:
private void checkName() {
if (etName.getText().toString().isEmpty()) {
Toast toast = Toast.makeText(this, "Please enter your name", Toast.LENGTH_LONG);
toast.show();
} else {
submit();
}
}
What happens is you are creating new toasts each time checkName() is called, hence they are "queued" by the system and shown one after another. You can try the following to ensure you are just making one toast and simply show it when needed:
Toast mToast;
private void checkName() {
if (etName.getText().toString().isEmpty()) {
if (mToast == null) { // Initialize toast if needed
mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
}
mToast.setText("Please enter your name"); // Simply set the text of the toast
mToast.show(); // Show it, or just refresh the duration if it's already shown
} else {
submit();
}
}