CountDownTimer behaves weird/different the second time i open its Activity - countdowntimer

I have been spending way too many hours on this one. And i just dont get it.
What i want: I have a main Activity (lets call it 'Activity Main') from which i am calling a second Activity ('Activity Timer') that has a CountDownTimer. Upon starting "Activity Timer" i want a Countdown to start running; it is only supposed to play a sound when it finishes. There is also a 'Pause-Button' which pauses/resumes the Countdown. 'Activity Timer' sends back results to 'Activity Main' via Intent when a button is pressed (either 'Success' or 'Fail' - well, it's a game). I am back at 'Activity Main' and all just worked perfectly fine.
That is until i start 'Activity Timer' a second time (for the secound round): The Countdown starts but cannot be paused. It just keeps ticking, even though i cancel() the Countdown and finish() the 'Activity Timer'.
Here's the code:
Activity Timer
public class GameActivity extends AppCompatActivity {
long countdown_time;
Button button_fail, button_success;
ImageButton imgbtn_pause;
boolean cd_running = false;
boolean countdown_auto = true;
TextView textView_countdown;
private static CountDownTimer;
Vibrator vibrator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Preferences
prefs = getSharedPreferences("shared_preferences", Context.MODE_PRIVATE);
// Intent
Intent i = getIntent();
countdown_time = i.getLongExtra("countdown_time", 60000);
// Assigning
button_fail = (Button) findViewById(R.id.btn_fail);
button_success = (Button) findViewById(R.id.btn_success);
textView_countdown = (TextView) findViewById(R.id.tv_countdown);
imgbtn_pause = (ImageButton) findViewById(R.id.imgbtn_pause);
button_fail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cd_running) {
countdown.cancel();
}
cd_running = false;
countdown = null;
Intent returnIntent = new Intent();
if (risk) {
returnIntent.putExtra("result", "-3");
} else {
returnIntent.putExtra("result", "0");
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
button_success.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cd_running) {
countdown.cancel();
}
cd_running = false;
countdown = null;
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
imgbtn_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cd_running) {
countdown.cancel();
cd_running = false;
imgbtn_pause.setBackgroundResource(R.drawable.play_2);
} else {
startCountDownTimer();
imgbtn_risk.setVisibility(View.INVISIBLE);
imgbtn_pause.setBackgroundResource(R.drawable.pause_2);
}
}
});
private void startCountDownTimer() {
cd_running = true;
imgbtn_pause.setBackgroundResource(R.drawable.pause_2);
countdown = new CountDownTimer(countdown_time, 1000) {
public void onTick(long millisUntilFinished) {
countdown_time = millisUntilFinished;
textView_countdown.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
countdown.cancel();
countdown = null;
cd_running = false;
if (!mute) {
vibrator = (Vibrator) GameActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
countdown_sound.start();
}
textView_countdown.setVisibility(View.INVISIBLE);
textView_gameOver.setVisibility(View.VISIBLE);
imgbtn_pause.setVisibility(View.INVISIBLE);
}
}.start();
}
The call from 'Activity Main':
#Override
public void onClick(View view) {
Intent i = new Intent(GameMenu.this, GameActivity.class);
i.putExtra("countdown_time", countdown_time);
startActivityForResult(i, 1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String result_string = data.getStringExtra("result");
int result_int = Integer.parseInt(data.getStringExtra("result"));
}
if (resultCode == Activity.RESULT_CANCELED) {
// No result
}
}

Related

How About onActivityResult when I want to read multiple file from storage

How About onActivityResult when I want to read multiple file form storage
In this xml form I have to take multiple image file by clicking different different button from the app external storage but their is a difficulties on ActivityResult override method calling , because it call automatically and can't be call multiple time for for different different button
It's working fine for single file picking and get image URI.
So how can I fix the ActivityResult override method for different different button in a single activity
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static final int PICK_PHOTO = 1958;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, PICK_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
}
}
Taking a array to pick photo then check with if else statement by array index
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static int[] PICK_PHOTO={0,1,2,3,4,5} ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.appBar.title.setText("লাইসেন্সের জন্য আবেদন করুন");
binding.appBar.back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 0);
}
});
binding.form4.chooseBankCertificate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[0]) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[1]) {
Uri imageUri = data.getData();
binding.form4.selectedBankCertificate.setText("" + imageUri.getLastPathSegment());
}
}
}

Dispose Device.StartTimer, if current page is reinitialized from the mainpage

I want to stop Device.StartTimer when my current page is re-initialize from the App.cs page, but every time when page is re-initialize Device.Starttimer create new instance and function is calling multiple times.
from the links and references i get to know that it will not stop until return statement not execute, but in my case how to execute return statement outside the method, that i can not understand.
Below is my cs page code.
public partial class MediaScreen : ContentPage
{
public static readonly List<string> ImageExtensions = new List<string>
{ ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" };
public static readonly List<string> videoExtensions = new List<string> {
".WAV", ".MID", ".MIDI", ".WMA", ".OGG", ".RMA", //etc
".AVI", ".MP4", ".DIVX", ".WMV", //etc
};
int i = 0;
DisplayInfo mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
public MediaScreen()
{
InitializeComponent();
try
{
StartPlaying();
}
catch (Exception e)
{
}
}
public bool StartPlaying()
{
CrossMediaManager.Current.Stop();
if (i == App.localStorage.Playlist.PlayListItems.Count)
{
i = 0;
StartPlaying();
return false;
}
var data = App.localStorage.Playlist.PlayListItems[i].MediaLibrary;
string fileName = App.path + "\\" + Path.GetFileName(data.Url);
if (ImageExtensions.Contains(Path.GetExtension(fileName).ToUpperInvariant()))
{
// process image
imgPlayer.IsVisible = true;
imgPlayer.Source = fileName;
videoPlayer.IsVisible = false;
}
else
{
try
{
CrossMediaManager.Current.Play(fileName);
CrossMediaManager.Current.MediaItemFinished += finishVideo;
videoPlayer.IsVisible = true;
imgPlayer.IsVisible = false;
}
catch (Exception e1)
{
}
}
i++;
Device.StartTimer(TimeSpan.FromSeconds
(data.Duration), StartPlaying);
return false;
}
}
}
You can use a stoppable timer instead. It has 2 goals: it can be stopped, it can be rescheduled (if it didn't start yet you can reschedule it):
Schedule example:
public StoppableTimer<object> timerScheduled; //object is param type you want
public void LaunchTimer()
{
if (timerScheduled == null)
{
timerScheduled = new StoppableTimer<object>(TimeSpan.FromSeconds(2), OnTimerStart);
timerScheduled.Start(null); //whatever param
}
else
{
//relaunch
timerScheduled.Stop();
timerScheduled.Start(control);
}
}
So when you need to cancel the timer just call timerScheduled.Stop();
Your callback:
private void OnTimerStart(object p)
{
//StartPlaying - do your stuff
}
Class:
public class StoppableTimer<T> // T is the parameter you want to pass to timer
{
private readonly TimeSpan timespan;
private readonly Action<T> callback;
private CancellationTokenSource cancellation;
public StoppableTimer(TimeSpan timespan, Action<T> callback)
{
this.timespan = timespan;
this.callback = callback;
this.cancellation = new CancellationTokenSource();
}
public void Start(T param)
{
CancellationTokenSource cts = this.cancellation; // safe copy
Device.StartTimer(this.timespan,
() => {
if (cts.IsCancellationRequested) return false;
this.callback.Invoke(param);
return false; // or true for periodic behavior
});
}
public void Stop()
{
Interlocked.Exchange(ref this.cancellation, new CancellationTokenSource()).Cancel();
}
public void Dispose()
{
}
}

Best approach to use DiffUtil with LIveData + Room Database?

I am using Room Database with LiveData , but my Local Database is updating too fast as per our requirement and at the same time i have to reload my recycler view .instead of calling notifyDataSetChanged() to adapter , i am trying to use DiffUtil , but is crashing or not reloading properly , this is uncertain .
i am following this tutorial :
Tutorials Link here
MyAdapter :
public class SwitchGridAdapter extends RecyclerView.Adapter<SwitchGridAdapter.ViewHolder> {
private List<Object> allItemsList;
private LayoutInflater mInflater;
private OnItemClickListener mClickListener;
private Context context;
private Queue<List<Object>> pendingUpdates =
new ArrayDeque<>();
// data is passed into the constructor
public SwitchGridAdapter(Context context,List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
allItemsList = new ArrayList<>();
if (applianceList!=null) allItemsList.addAll(applianceList);
if (zmoteRemoteList!=null)allItemsList.addAll(zmoteRemoteList);
}
// inflates the cell layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R .layout.switch_grid_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the textview in each cell
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Doing some update with UI Elements
}
// total number of cells
#Override
public int getItemCount() {
return allItemsList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener {
TextView myTextView;
ImageView imgSwitch;
ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.txtSwitchName);
imgSwitch = (ImageView) itemView.findViewById(R.id.imgSwitchStatus);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
// handling click
}
#Override
public boolean onLongClick(View view) {
return true;
}
// convenience method for getting data at click position
Object getItem(int id) {
return allItemsList.get(id);
}
// allows clicks events to be caught
public void setClickListener(OnItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongPressListner(View view, int position);
}
// ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
// From This Line Reloading with Diff Util is Done .
//✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
public void setApplianceList( List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList)
{
if (allItemsList == null)
allItemsList = new ArrayList<>();
List<Object> newAppliances = new ArrayList<>();
if (applianceList!=null) newAppliances.addAll(applianceList);
updateItems(newAppliances);
}
// when new data becomes available
public void updateItems(final List<Object> newItems) {
pendingUpdates.add(newItems);
if (pendingUpdates.size() > 1) {
return;
}
updateItemsInternal(newItems);
}
// This method does the heavy lifting of
// pushing the work to the background thread
void updateItemsInternal(final List<Object> newItems) {
final List<Object> oldItems = new ArrayList<>(this.allItemsList);
final Handler handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
final DiffUtil.DiffResult diffResult =
DiffUtil.calculateDiff(new DiffUtilHelper(oldItems, newItems));
handler.post(new Runnable() {
#Override
public void run() {
applyDiffResult(newItems, diffResult);
}
});
}
}).start();
}
// This method is called when the background work is done
protected void applyDiffResult(List<Object> newItems,
DiffUtil.DiffResult diffResult) {
dispatchUpdates(newItems, diffResult);
}
// This method does the work of actually updating
// the backing data and notifying the adapter
protected void dispatchUpdates(List<Object> newItems,
DiffUtil.DiffResult diffResult) {
// ❌❌❌❌❌❌ Next Line is Crashing the app ❌❌❌❌❌
pendingUpdates.remove();
dispatchUpdates(newItems, diffResult);
if (pendingUpdates.size() > 0) {
updateItemsInternal(pendingUpdates.peek());
}
}
}
Observing LiveData
public void setUpAppliancesListLiveData()
{
if (applianceObserver!=null)
{
applianceObserver = null;
}
Log.e("Appliance Fetch","RoomName:"+this.roomName);
applianceObserver = new Observer<List<Appliance>>() {
#Override
public void onChanged(#Nullable List<Appliance> applianceEntities) {
// Log.e("Appliance Result","Appliance List \n\n:"+applianceEntities.toString());
new Thread(new Runnable() {
#Override
public void run() {
List<Appliance> applianceListTemp = applianceEntities;
zmoteRemoteList = new ArrayList<>(); //appDelegate.getDatabase().zmoteRemoteDao().getRemoteList(roomName);
// Sort according to name
Collections.sort(applianceListTemp, new Comparator<Appliance>() {
#Override
public int compare(Appliance item, Appliance t1) {
String s1 = item.getSwitchName();
String s2 = t1.getSwitchName();
return s1.compareToIgnoreCase(s2);
}
});
if(getActivity()!=null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
applianceList = applianceListTemp;
mRecyclerView.getRecycledViewPool().clear();
adapter.setApplianceList(applianceList,zmoteRemoteList);
}
});
}
}
}).start();
}
};
appDelegate.getDatabase().applianceDao().getApplinaceListByRoomName(this.roomName).observe(this, applianceObserver);
}

How can we make app in kiosk mode using xamarin?

I'm creating new app using xamarin. I have already completed some part using some sample codes. I'm able to disable back buttons, volume buttons and power button.
But when trying to disable home button I'm getting error on debugging.
I'm following this link,Kiosk mode in Andriod.
But when trying to disable home button I'm getting error on debugging.
Since you didn't post your code and your error message, we don't know what happened, I just tried to create such a sample followed the blog your posted and it works fine by my side.
Here is the service:
namespace KioskModeAndroid
{
[Service]
[IntentFilter(new[] { "KioskModeAndroid.KioskService" })]
public class KioskService : Service
{
private static long INTERVAL = Java.Util.Concurrent.TimeUnit.Seconds.ToMillis(2);
private static string TAG = typeof(KioskService).Name;
private static string PREF_KIOSK_MODE = "pref_kiosk_mode";
private Thread t = null;
private Context ctx = null;
private bool running = false;
public override void OnDestroy()
{
Log.Info(TAG, "Stopping service 'KioskService'");
running = false;
base.OnDestroy();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Log.Info(TAG, "Starting service 'KioskService'");
running = true;
ctx = this;
t = new Thread(() =>
{
while (running)
{
handleKioskMode();
Thread.Sleep(INTERVAL);
}
StopSelf();
});
t.Start();
return StartCommandResult.NotSticky;
}
private void handleKioskMode()
{
if (isKioskModeActive(ctx))
{
}
if (isInBackground())
{
restoreApp();
}
}
private bool isKioskModeActive(Context context)
{
var sp = PreferenceManager.GetDefaultSharedPreferences(context);
return sp.GetBoolean(PREF_KIOSK_MODE, false);
}
private bool isInBackground()
{
var am = ctx.GetSystemService(Context.ActivityService) as ActivityManager;
var processes = am.RunningAppProcesses;
foreach (var process in processes)
{
if (process.Importance == ActivityManager.RunningAppProcessInfo.ImportanceForeground)
{
foreach (var activeprocess in process.PkgList)
{
if (activeprocess == ctx.PackageName)
return false;
}
}
}
return true;
}
private void restoreApp()
{
Intent i = new Intent(ctx, typeof(MainActivity));
i.AddFlags(ActivityFlags.NewTask);
ctx.StartActivity(i);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
}
I started this service in the OnCreate of MainActivity:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
StartService(new Intent(this, typeof(KioskService)));
}

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

Resources