Android Studio - Displaying List View Inside AlertDialog

Android Studio - Displaying List View Inside AlertDialog


1.) Follow this code:
================
>Note: custom_dialog_layout.xml is the layout that will pop-up
>Note: row.xml is the item used for populating row
AlertDialog.Builder  builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Holo));

builder.setTitle("Custom Dialog");

View customView = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_dialog_layout, null, false);

ListView listList1 = (ListView)customView.findViewById(R.id.listView1);
String[] stringArray1 = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter adapter1 = new MyListAdapter(MainActivity.this, R.layout.row, stringArray1);
listList1.setAdapter(adapter1);

builder.setView(customView);

builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Ok

}
});

builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Cancel
}
});

builder.show();

Android Studio - Creating Material Design App Bar

Android Studio - Creating Material Design App Bar


1.) Set-up the color that we'll use for the app bar:
========================================
>Create a new xml inside values and name it color.xml
<resources>
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>
</resources>

2.) Using the previously declared color, change the style.xml to apply the colors:
=================================================================

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/ColorPrimary</item>
<item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
<!-- Customize your theme here. -->
</style>
</resources>

3.) Make a tool bar:
================
>Create a new xml layout file and name it tool_bar.xml
<span style="font-size: x-small;"><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/ColorPrimary"
android:elevation="4dp"

>

</android.support.v7.widget.Toolbar>

</span>

4.) Use the tool bar:
================
>Insert this code to wherever xml layout you want to display the tool bar
<include
android:id="@+id/tool_bar"
layout="@layout/tool_bar"
></include>

5.) Adding additional buttons inside the app bar:
=======================================
>Go to menu_main.xml and add/paste the code below
 <item
android:id="@+id/action_user"
android:orderInCategory="300"
android:title="User"
android:icon="@drawable/ic_launcher"
app:showAsAction="ifRoom"></item>

Gresk gjeld bør ikke slettes

Det er ikke rasjonelt å slette gresk gjeld nå. Hellas må kunne vise til resultater først, slik at landet ikke forblir et evig pengesluk.

En lang rekke norske og utenlandske høyt ansett akademikere og IMF ønsker store kutt i gresk gjeld. De har selvsagt helt rett i at Hellas aldri vil bli i stand til å betjene en gjeld på 175 % av BNP. Spørsmålet er derfor når og ikke om gjeld skal slettes. Å slette gjelden nå er likevel en dårlig idé.

EU ønsker sannsynligvis ikke å kutte gjelden før de ser en bærekraftig gresk økonomi. Store gjeldskutt vil svekke kreditorenes makt. Av erfaring vil Hellas trolig bruke en slik mulighet til å hindre nødvendige strukturelle reformer.

Erfaringen viser at Hellas selv ikke er i stand til å gjennomføre reformene på eget initiativ. De må tvinges gjennom. Da er det dumt å gi fra seg det sterkeste forhandlingskortet på forhånd. Kredittselskap kutter ikke gjelden din før du har vist vilje til å endre adferd. Det kan hende EU resonerer slik overfor Hellas også.

Størrelsen på grekernes nominelle gjeld er tross alt av ganske underordnet betydning. Det avgjørende er kontantstrømmen og ikke regnskapet. Dette er noe av det første våre finansstudenter lærer.

I stedet for gjeldsslette får Hellas nå hjelp fra kreditorene i form av subsidiert rente og lang tilbakebetalingstid. Europamesteren i statsgjeld betaler derfor relativt lite til kreditorene sammenlignet med andre kriseland. Gjeldsbyrden er høyst overkommelig for grekerne.

Løsningen er derfor ikke gjeldskutt nå. Landet sliter med utstrakt korrupsjon, kameraderi, et råttent skattesystem, generøse pensjonsordninger og en ineffektiv statlig sektor. Det er liten vits i å slette gjeld uten at disse problemene er håndtert.

Som Jens Frølich Holte nevner et innsiktsfullt innlegg i mandagens DN, så har Hellas blitt satt under administrasjon før, i 1898. Det resulterte i en bemerkelsesverdig velstandsutvikling. Kjøpekraftsjustert netto nasjonalprodukt (NNP) økte med godt over fire hundre prosent de neste førti årene mens utlendinger styrte butikken. Ingen andre vestlige land var i nærheten av en slik eventyrlig vekst.

Det bør kanskje nevnes at den russiske revolusjon leverte en vekst på vanvittige to tusen prosent i samme periode. Det er likevel liten grunn til å tro at kommunisme vil gi samme resultat i Hellas i dag. Det beste for grekerne på sikt er derfor også denne gang at utlendinger tar over styringen, selv om det vil gå ut over grekernes selvfølelse.

Per i dag klarer ikke Hellas en gang å oppnå overskudd før gjeldsbetaling, selv etter ekstreme kutt i offentlig sektor. Uten strukturelle reformer må gjelden derfor sannsynligvis skrives ned til nær null for å være betjenbar.

Reformer er altså helt nødvendig og burde helst vært koblet med motkonjunkturpolitikk og ikke kutt. Kjente akademikere som Joseph Stiglitz har argumentert sterkt for dette. Stiglitz og andre ser imidlertid helt bort fra at det ikke finnes noe land i verden som vil putte mer penger i Hellas sin bunnløse kasse før reformene er på plass.

Å kutte gjelden og gi Hellas et «lykke til» vil bare medføre at de samme problemene dukker opp igjen. Det er viktigere å gjøre strukturelle endringer slik som at skatter faktisk blir innkrevd, at hull i skattesystemet tettes, at pensjonssystemet ikke er mer generøst enn kreditorenes og så videre. Dessverre er det lite sannsynlig at grekerne selv tar initiativ til å løse disse problemene.

Grekerne er ikke som gruppe late, men arbeidsbyrden er veldig ujevnt fordelt. Byråkratiet er håpløst ineffektivt og korrupsjon er utbredt. De som ikke har vernet arbeidsplass i byråkratiet må jobbe tilsvarende mer. Hellas er i dag i en tragisk situasjon, men landet har et enormt potensial som EU trolig ønsker å se før gjeld kuttes.





Poland and the United States: all that begins must end


With my previous entry, I wrapped up an impromptu series of articles that chronicled my childhood experiences in Poland and compared the culture I grew up with to the American society that I'm living in today. For the readers who want to be able to navigate the series without scrolling endlessly, I wanted to put together a quick table of contents. Here it goes.




The entry that started it all:





  • "On journeys" - a personal story recounting my travels from Poland to the US.




Oh, the places you won't go:






Poland (and Europe) vs the United States:





And now, back to the regularly scheduled programming...

Poland vs the United States: American exceptionalism


This is the fourteenth article talking about Poland, Europe, and the United States. To explore the entire collection, start here.




This is destined to be the final entry in the series that opened with a chronicle of my journey from Poland to the United States, only to veer into some of the most interesting social differences between America and the old continent. There are many other topics I could still write about - anything from the school system, to religion, to the driving culture - but with my parental leave coming to an end, I decided to draw a line. I'm sure that this decision will come as a relief for those who read the blog for technical insights, rather than political commentary :-)




The final topic I wanted to talk about is something that truly irks some of my European friends: the belief, held deeply by many Americans, that their country is the proverbial "city upon a hill" - a shining beacon of liberty and righteousness, blessed by the maker with the moral right to shape the world - be it by flexing its economic and diplomatic muscles, or with its sheer military might.




It is an interesting phenomenon, and one that certainly isn't exclusive to the United States. In fact, expansive exceptionalism used to be a very strong theme in the European doctrine long before it emerged in other parts of the Western world. For one, it underpinned many of the British, French, Spanish, and Dutch colonial conquests over the past 500 years. The romanticized notion of Sonderweg played a menacing role in German political discourse, too - eventually culminating in the rise of the Nazi ideology and the onset of World War II. It wasn't until the defeat of the Third Reich when Europe, faced with unspeakable destruction and unprecedented loss of life, made a concerted effort to root out many of its nationalist sentiments and embrace a more harmonious, collective path as a single European community.




America, in a way, experienced the opposite: although it has always celebrated its own rejection of feudalism and monarchism - and in that sense, it had a robust claim to being a pretty unique corner of the world - the country largely shied away from global politics, participating only very reluctantly in World War I, then hoping to wait out World War II up until being attacked by Japan. Its conviction about its special role on the world stage has solidified only after it paid a tremendous price to help defeat the Germans, to stop the march of the Red Army through the continent, and to build a prosperous and peaceful Europe; given the remarkable significance of this feat, the post-war sentiments in America may be not hard to understand. In that way, the roots of American exceptionalism differed from its European predecessors, being fueled by a fairly pure sense of righteousness - and not by anger, by a sense of injury, or by territorial demands.




Of course, the new superpower has also learned that its military might has its limits, facing humiliating defeats in some of the proxy wars with the Soviets and seeing an endless spiral of violence in the Middle East. The voices predicting its imminent demise, invariably present from the earliest days of the republic, have grown stronger and more confident over the past 50 years. But the country remains a military and economic powerhouse; and in some ways, its trigger-happy politicians provide a counterbalance to the other superpowers' greater propensity to turn a blind eye to humanitarian crises and to genocide. It's quite possible that without the United States arming its allies and tempering the appetites of Russia, North Korea, or China, the world would have been a less happy place. It's just as likely that the Middle East would have been a happier one.




Some Europeans show indignation that Americans, with their seemingly know-it-all attitudes toward the rest of the world, still struggle to pinpoint Austria or Belgium on the map. It is certainly true that the media in the US pays little attention to the old continent. But deep down inside, European outlets don't necessarily fare a lot better, often focusing its international coverage on the silly and the formulaic: when in Europe, you are far more likely to hear about a daring rescue of a cat stuck on a tree in Wyoming, or about the Creation Museum in Kentucky, than you are to learn anything substantive about Obamacare. (And speaking of Wyoming and Kentucky, pinpointing these places on the map probably wouldn't be the European viewer's strongest feat). In the end, Europeans who think they understand the intricacies of US politics are probably about as wrong as the average American making sweeping generalizations about Europe.




And on that intentionally self-deprecating note, it's time to wrap the series up.

Poland vs the United States: work and entitlements


This is the thirteenth article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




In one of my earlier posts, I alluded to the pervasive faith in the American Dream: the national ethos of opportunity, self-sufficiency, and free enterprise that influences the political discourse in the United States. The egalitarian promise of the American Dream is simple: no matter who you are, hard work and ingenuity will surely allow you to achieve your dreams. From that, it follows that on your journey, you are not entitled to much; the government will be there to protect your freedom, but it will not give you a head start.




Unlike many of my peers, I suspect that there is truth to the cliche; the United States is a remarkably industrious nation and the home to many of the world's most innovative and fastest-growing businesses. It certainly treads ahead of European economies, still dominated by pre-war industrial conglomerates and former state monopolists, and weighed down by aging populations, highly regulated markets, and inflexible, out-of-control costs. America's mostly-self-made magnates, the likes of Elon Musk, Bill Gates, and Warren Buffett, are also far more likable and seemingly more human than Europe's stereotypical caste of aristocratic families and shadowy oligarchs.




On the flip side, the striking upward mobility of rags-to-riches icons such as Steve Jobs or Oprah Winfrey tends to be an exception, not a rule. Many scholars point out that parents' incomes are highly predictive of the incomes of their children - and that in the US, this effect is more pronounced than in some of the European states. Such studies can be misleading, because in less unequal EU societies, moving to a higher income quantile may confer no substantial change in the quality of life - but ultimately, there is no denying that people who are born into poor families will usually remain poor for the rest of their lives. And with the contemporary trends in outsourcing and industrial automation, the opportunities for unskilled blue collar labor - once a key stepping stone in the story of the American Dream - are shrinking fast.




In contrast with the United States, many in Europe reject Milton Friedman's views on consensual capitalism and hold that it is a basic human right to be able to live a good life or to have an honest and respectable job. This starts with the labor law: in much of the United States, firing an employee can happen in the blink of an eye, for almost any reason - or without giving a reason at all. In Europe, the employer will need a just cause and will go through a lengthy severance period; depending on the circumstances, the company may be also barred from hiring another person to do the same job. Employment benefits follow the same pattern; in the US, paid leave is largely up to employers to decide, with skilled workers being lured with packages that would make Europeans jealous - but many unskilled laborers, especially in the retail and restaurant business, getting the short end of that stick.




In Europe, enabling the disadvantaged to contribute to the society and to live fulfilling lives is also a matter of government policy, often implemented through sweeping wealth redistribution - or through public-sector employment orchestrated at a scale that rivals that of quasi-communist China and other authoritarian countries (for example, in France and Greece, about one in three jobs is run by the state). Such efforts tend to be more successful in small and wealthy Scandinavian countries, where the society can be engineered with more finesse. In many other parts of the continent, systemic, long-term poverty is still rampant, with the government being able to do little more than providing people with a lifetime of subsidized basic sustenance and squalor living conditions. Ultimately, when it comes to combating multi-generational poverty, financial aid administered by sprawling national bureaucracies is not always a cure-all.




Perhaps interestingly, the benefits that are most frequently described as inadequate in the US are not as strikingly different from what one would be entitled to in the EU. For example, the minimal wage is quite comparable; it is around $2.60 per hour in Poland, about $3.70 in Greece, some $9.30 in Germany, and in the ballpark of $10.00 in the UK. In the US, the national average hovers somewhere around $8.00, with some of the states with higher costs of living on track to raise it to $10.00 within a year or two; in fact, some progressive municipalities are aiming for $15.




Unemployment and retirement benefits, although certainly not lavish, also follow the same pattern. When it comes to unemployment in particular, in the States, workers are entitled to about half of their previous salary for up to six months - although that period has been routinely extended in times of economic calamity. In Europe, the figures are roughly comparable, with payments in the ballpark of 50-70% of your previous salary, typically extending for somewhere between 6 and 12 months. The main difference is that the upper limit for monthly benefits tends to be significantly lower in the US than in Europe, often putting far greater strain on single-income families in places with high cost of living. In France, the ceiling seems to be around $8,000 a month; in the US, you will probably see no more than $2,000.




Another overlooked dimension of this debate is the unique tradition of charitable giving in the United States - a phenomenon that allows private charities to provide extensive assistance to people in need. Such giving happens on a staggering scale, with citizens donating more than $350 billion a year - more than twenty times the amount donated in the UK. The bulk of that money goes to organization that provide food, shelter, and counseling to the poor. It is an interesting model, with its own share of benefits and trade-offs: private charities operate on a more local scale and have a far stronger incentive to spend money wisely and provide meaningful aid. On the flip side, their reach is not as universal - and the benefits are not guaranteed.




Many of the conservatives who preach the virtues of the American Dream vastly underestimate the pervasive and lasting consequences of being born into poverty or falling onto hard times; they also underestimate the role that unearned privilege and luck played in their own lives. The progressives often do no better, seeing European social democracies as a flawless role model, even in the midst of the enduring sovereign debt crisis in the eurozone; breathlessly reciting knock-off Marxist slogans; and portraying the rich as Mr. Burns-esque villains of unfathomable wealth, motivated by just two goals: to exploit the working class and to avoid paying taxes at any cost. In the end, helping the disadvantaged is a moral imperative - but many ideas sound better on a banner than when implemented as a government policy.




For the next and final article in the series, click here.

Poland vs the United States: governance


This is the twelfth article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




The American model of government is a complex beast. To a visitor from continental Europe, accustomed to the Napoleonic traditions of civil law and to the political realities of unitary states, the sight can be also a bit perplexing: after all, how does a country of this size prosper with a bitterly partisan, gridlocked Congress that repeatedly fails to even pass the budget on time? And how is it possible that, with an approval rating of 15%, the elected officials are not facing a wave of widespread social unrest?




I suspect that the key to solving this riddle lies in the fact that the United States is still very much a federation of self-governing states - and that most of the decisions that affect the lives of ordinary citizens are not made in Washington. Each and every state establishes its own criminal and civil law, levies its own taxes, runs its own welfare systems, and appoints its own judges - sometimes by popular vote. In fact, the states routinely confer far-reaching powers onto individual municipalities: for example, most towns and counties operate their own, completely autonomous police departments that respond to local officials, not to a career politician on the East Coast.




All this makes the government feel quite different from what you are likely to experience in Europe. Let's stick to law enforcement: in Poland and in some other European states, where the police are a part of a sprawling national bureaucracy, the citizens may have very few options for addressing concerns that do not rise to the level of national debate. In the US, dismantling the entire police force may seem trivial in comparison: the concerned citizens may need to get a local newspaper interested in their cause, then band together to recall the local official who is ultimately on the hook. Of course, the independence comes at a price: small, self-funded police departments can be quicker to adopt questionable practices that would not stand to broader scrutiny, such as racial profiling or the rash application of civil forfeiture.




When it comes to the role of the federal government, the picture is complicated. In principle, the constitution gives it only a couple of duties; for example, the feds control various aspects of interstate commerce, print money, maintain armed forces, and handle foreign affairs. Of course, over the years, their responsibilities have expanded considerably, with the legislators exploiting the vagueness of the concept of "interstate commerce" in all sorts of creative ways. Today, the ongoing debate about the appropriate boundaries of this practice fuels the partisan gridlock in Washington. Modern-day Republicans, swayed by the conservative Tea Party movement, argue that the feds should honor the vision of the Founding Fathers and not meddle in the affairs of the states. The Democratic party, taking notes from the vaguely leftist Occupy campaign, increasingly sees the federal government as a flexible tool for establishing country-wide standards of environmental protection, labor rights, welfare, gun control, education, and other progressive causes historically associated with European social democrats.




On that matter, the voters themselves seem to be split. In polls, a robust majority of Americans declare that their government regulates too many aspects of their lives, tries to solve too many problems, wields too much control, and is inherently less efficient and less fair than private enterprises; about two-thirds of respondents see the feds as more of a problem than a solution, and a shocking 50% believe that the apparatus poses an immediate and serious threat to civil liberties. Yet, despite holding views that would make Milton Friedman proud, when asked about specific programs and entitlements - be it defense spending or Medicare - most voters oppose budget cuts. Ultimately, the equally powerful distrust of big corporations, coupled with the allure of European-style welfare systems, often sends the public into the embrace of big-government progressives who promise to solve a growing range of societal ills using federal-level income redistribution and overarching legislative frameworks.




Either way, owing to the parties' newly-found tendency to pander to populist fringes and their inability to compromise, the dysfunctional Congress gets very little love from the average voter; but somewhat paradoxically, the representatives from each and every district are usually well-liked by their own constituents and get reelected with ease. Some blame gerrymandering, but a simpler explanation exists: most of the candidates have strong ties to the districts they represent, many of them having a track record as local politicians or successful businessmen. As a result, they understand what matters to their constituents and often meaningfully work to advance that agenda. They also live and die at the mercy of local newspapers, sometimes lending a hand to the voters who write or call them to resolve bureaucratic hurdles and address other everyday grievances. The practice of getting your representatives involved in such matters is almost unthinkable in Poland, where the slots on local ballots are traded by party officials - and are routinely handed out to people with little or no connection to the region they are supposed to represent.




With American political campaigns financed from private funds, it is often argued that the representatives in Congress are disproportionately influenced by the wealthy few and by a variety of organized lobby groups. This is likely true, although the disparity is at least partly offset by the public's fascination with human interest stories and the tendency to root for the common folk. Ultimately, even the most cynical congresspeople can afford to be persuaded by money only when it comes to the topics that their constituents are fairly indifferent to.




Beyond the legislative and executive branches of the government, some distinct undertones of self-governance are present in the US judicial system, too. The country borrows from the traditions of British common law, rather than the civil law system utilized in much of continental Europe. It embraces the significance of legal precedent and emphasizes humanist values over the strict application of legal codes, with remarkably broad powers vested in the judges and in the juries of peers - up to the notion of jury nullification. Ultimately, the system seeks to limit the consequences of the fallibility of legislators, who often struggle to properly consider all the implications of the laws they pass; it trades it for the increased risk of fallible courts - who bring in their own subconscious biases into the mix.




For the next article in the series, click here.