[Q] Beginner Problem with Java&Android - Java for Android App Development

This is I'm guessing a beginner problem but here i go. I have a text game I've been toying around with in c# using the console to output the text of the game. Recently i got an android tablet and downloaded AIDE to see if I could make something similar since Java and C# are similar. So far I've gotten four buttons and made a simple app that outputs a different line of text per button press. What im now having trouble with is using a loop similar to the ones I use in the C# game. I'm trying to avoid creating a different activity for every screen if possible. Its probably easier just to show the code im using. When ran the buttons dont show and it just stalls. Any help would be greatly appreciated.
public class MainActivity extends Activity
{
int choice;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
Gameloop(choice);
// super.finish();
}
public void Buttons()
{
Button bt1 = (Button) findViewById(R.id.b1);
Button bt2 = (Button) findViewById(R.id.b2);
Button bt3 = (Button) findViewById(R.id.b3);
Button bt4 = (Button) findViewById(R.id.b4);
bt1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 1;
}
});
bt2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 2;
}
});
bt3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 3;
}
});
bt4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 4;
}
});}
public void Gameloop(int choice)
{
boolean Game = true;
boolean game = true;
TextView gameV = (TextView) findViewById(R.id.game);
gameV.setText("Loop Test");
do
{
do
{
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 2");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 2");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 2");
gameV.setTextSize(45);
}
if (choice == 4)
{
game = false;
}
}
while (game == true);
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 1");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 1");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 1");
gameV.setTextSize(45);
}
if (choice == 4)
{
Game = false;
}
}
while (Game == true);
}

put your code in [.code] brackets so its easier for us to read.
i dont know c#, but java would be more if/else statements, not endless ifs.
and where you have the (onclick, choice=3) sections, take that out and do yous set texts inside each different button click.
and you do have an xml with the buttons layout right?

You cannot have a loop method like that in Android. It would block the UI Thread and then it wouldn't register a ButtonClick. Android already has a Looper! If you really need to do it like that you can create a second Thread.
But I would just put your .setText(...) in the onClickListeners!

If you have already developed it for C#, why do you not programm it for Android in C#, too?
Have a look at this post: [GUIDE]C# for Android----for Starters----UPDATED
And this forum with more guides related to the C languages (including C#): http://forum.xda-developers.com/forumdisplay.php?f=2198
Btw, please put your code in
Code:
tags for better readability. ;)

Thanks for the replies. My first attempt at using Android was to simply have each of the four button presses return a line of text in the textview. Such as i press button one and the textview shows "Youve pressed button one". I was trying to attempt something similar but with loops. I do have an xml for the layout, my first attempt was within each onclick method for each button had a single textview setText. Here's the code with the loops.
Code:
public class MainActivity extends Activity
{
int choice;
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
Gameloop(choice);
// super.finish();
}
public void Buttons()
{
Button bt1 = (Button) findViewById(R.id.b1);
Button bt2 = (Button) findViewById(R.id.b2);
Button bt3 = (Button) findViewById(R.id.b3);
Button bt4 = (Button) findViewById(R.id.b4);
bt1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 1;
}
});
bt2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 2;
}
});
bt3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 3;
}
});
bt4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 4;
}
});}
public void Gameloop(int choice)
{
boolean Game = true;
boolean game = true;
TextView gameV = (TextView) findViewById(R.id.game);
gameV.setText("Loop Test");
do
{
do
{
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 2");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 2");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 2");
gameV.setTextSize(45);
}
if (choice == 4)
{
game = false;
}
}
while (game == true);
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 1");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 1");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 1");
gameV.setTextSize(45);
}
if (choice == 4)
{
Game = false;
}
}
while (Game == true);
}

DChar21 said:
Thanks for the replies. My first attempt at using Android was to simply have each of the four button presses return a line of text in the textview. Such as i press button one and the textview shows "Youve pressed button one". I was trying to attempt something similar but with loops. I do have an xml for the layout, my first attempt was within each onclick method for each button had a single textview setText. Here's the code with the loops.
Code:
public class MainActivity extends Activity
{
int choice;
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
Gameloop(choice);
// super.finish();
}
public void Buttons()
{
Button bt1 = (Button) findViewById(R.id.b1);
Button bt2 = (Button) findViewById(R.id.b2);
Button bt3 = (Button) findViewById(R.id.b3);
Button bt4 = (Button) findViewById(R.id.b4);
bt1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 1;
}
});
bt2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 2;
}
});
bt3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 3;
}
});
bt4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 4;
}
});}
public void Gameloop(int choice)
{
boolean Game = true;
boolean game = true;
TextView gameV = (TextView) findViewById(R.id.game);
gameV.setText("Loop Test");
do
{
do
{
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 2");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 2");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 2");
gameV.setTextSize(45);
}
if (choice == 4)
{
game = false;
}
}
while (game == true);
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 1");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 1");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 1");
gameV.setTextSize(45);
}
if (choice == 4)
{
Game = false;
}
}
while (Game == true);
}
Click to expand...
Click to collapse
i think you can simplify your code in this way, and should work:
Code:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button bt1, bt2, bt3, bt4;
private TextView gameV;
private int choice;
private boolean game;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gameV = (TextView) findViewById(R.id.game);
bt1 = (Button) findViewById(R.id.b1);
bt2 = (Button) findViewById(R.id.b2);
bt3 = (Button) findViewById(R.id.b3);
bt4 = (Button) findViewById(R.id.b4);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.b1:
choice = 1;
//do something else on b1 click
gameV.setText("You've Pressed Button 1 Loop 2");
gameV.setTextSize(35);
//if needed add conditional statements or what you want
break;
case R.id.b2:
choice = 2;
gameV.setText("You've Pressed Button 2 Loop 2");
gameV.setTextSize(25);
//other code here
break;
case R.id.b3:
choice = 3;
gameV.setText("You've Pressed Button 3 Loop 2");
gameV.setTextSize(45);
//something else here
break;
case R.id.b4:
choice = 4;
game = false;
//do stuff
break;
}
}
}
hope it helps with your app :good:

DChar21 said:
Thanks for the replies. My first attempt at using Android was to simply have each of the four button presses return a line of text in the textview. Such as i press button one and the textview shows "Youve pressed button one". I was trying to attempt something similar but with loops. I do have an xml for the layout, my first attempt was within each onclick method for each button had a single textview setText. Here's the code with the loops.
Code:
public class MainActivity extends Activity
{
int choice;
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
Gameloop(choice);
// super.finish();
}
public void Buttons()
{
Button bt1 = (Button) findViewById(R.id.b1);
Button bt2 = (Button) findViewById(R.id.b2);
Button bt3 = (Button) findViewById(R.id.b3);
Button bt4 = (Button) findViewById(R.id.b4);
bt1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 1;
}
});
bt2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 2;
}
});
bt3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 3;
}
});
bt4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 4;
}
});}
public void Gameloop(int choice)
{
boolean Game = true;
boolean game = true;
TextView gameV = (TextView) findViewById(R.id.game);
gameV.setText("Loop Test");
do
{
do
{
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 2");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 2");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 2");
gameV.setTextSize(45);
}
if (choice == 4)
{
game = false;
}
}
while (game == true);
if (choice == 1)
{
gameV.setText("You've Pressed Button 1 Loop 1");
gameV.setTextSize(35);
}
if (choice == 2)
{
gameV.setText("You've Pressed Button 2 Loop 1");
gameV.setTextSize(25);
}
if (choice == 3)
{
gameV.setText("You've Pressed Button 3 Loop 1");
gameV.setTextSize(45);
}
if (choice == 4)
{
Game = false;
}
}
while (Game == true);
}
Click to expand...
Click to collapse
I have not been that patient to read your code with full patient. But I think, when you call gameLoop(choice) in onCreate. that value of choice has not been initialized. And when you declare your variables inside the Listeners. The compiler wont loop or go back to the onCreate method. So basically you should call gameLoop() inside your listener method.
Example:
Code:
bt2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
choice = 2;
Gameloop(choice);
}
});
This code can be made a little more precisely. You can use inner classes and switches... instead of using a buch of if-elses.
Again, I have not been patient enough, to go through the complete code. I may have been mistaken..
{ Hope it helps ! }

Related

[Q] ExpandableView inside another ExpandableView won't inflate children

I've been struggling for a couple of weeks to solve this problem. I have two expandable views, one inside another. Whenever i click on the second level expandable view items, it won't inflate its children. All i see when i click is a small scroll bar that appears on the right side on the expandable view item itself. Using a simple layout with a fixed textview results in the same behaviour, meaning that the problem isn't within the ShiftListItem object/s.
Also, getChildView() is never been called.
YearListAdapter:
Code:
public class YearListAdapter extends BaseExpandableListAdapter {
private Context _context;
private SparseArray<SparseArray<ArrayList<Salary>>> _shiftYears;
public YearListAdapter(
SparseArray<SparseArray<ArrayList<Salary>>> shiftYears,
Context context) {
super();
_context = context;
_shiftYears = shiftYears;
}
public Object getChild(int arg0, int arg1) {
return (null == _shiftYears.get(_shiftYears.keyAt(arg0))) ? null
: _shiftYears.get(_shiftYears.keyAt(arg0)).get(
_shiftYears.get(_shiftYears.keyAt(arg0)).keyAt(arg1));
}
public long getChildId(int arg0, int arg1) {
return arg1;
}
public View getChildView(int arg0, int arg1, boolean arg2,
View convertView, ViewGroup arg4) {
MonthsListView monthLevelExpandable = new MonthsListView(_context);
MonthListAdapter adapter = new MonthListAdapter(_context,
_shiftYears.get(_shiftYears.keyAt(arg0)));
monthLevelExpandable.setAdapter(adapter);
adapter.forceReload();
monthLevelExpandable.setGroupIndicator(null);
return monthLevelExpandable;
}
public int getChildrenCount(int arg0) {
if (null == _shiftYears.get(_shiftYears.keyAt(arg0)))
return 0;
return _shiftYears.get(_shiftYears.keyAt(arg0)).size();
}
public Object getGroup(int arg0) {
return (null == _shiftYears) ? null : _shiftYears.get(_shiftYears
.keyAt(arg0));
}
public int getGroupCount() {
return _shiftYears.size();
}
public long getGroupId(int arg0) {
return arg0;
}
public View getGroupView(int arg0, boolean isExpanded, View convertView,
ViewGroup arg3) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.year_list_view_item, null);
}
TextView title = (TextView) convertView.findViewById(R.id.yearTitle);
title.setText("" + _shiftYears.keyAt(arg0));
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
public void forceReload() {
notifyDataSetChanged();
}
}
MonthListAdapter:
Code:
public class MonthListAdapter extends BaseExpandableListAdapter {
private Context _context;
private SparseArray<ArrayList<Salary>> _shiftMonths;
public MonthListAdapter(Context context,
SparseArray<ArrayList<Salary>> shiftMonths) {
super();
_context = context;
_shiftMonths = shiftMonths;
}
public Object getChild(int groupPosition, int childPosition) {
return (null == _shiftMonths) ? null : _shiftMonths.get(
_shiftMonths.keyAt(groupPosition)).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ShiftListItem sli;
if (null == convertView) {
sli = (ShiftListItem) View.inflate(_context,
R.layout.shift_list_item, null);
} else {
sli = (ShiftListItem) convertView;
}
sli.setSalary(_shiftMonths.get(_shiftMonths.keyAt(groupPosition)).get(
childPosition));
return sli;
}
public int getChildrenCount(int groupPosition) {
if (null == _shiftMonths
|| null == _shiftMonths.get(_shiftMonths.keyAt(groupPosition)))
return 0;
return _shiftMonths.get(_shiftMonths.keyAt(groupPosition)).size();
}
public Object getGroup(int groupPosition) {
return (null == _shiftMonths) ? null : _shiftMonths.get(_shiftMonths
.keyAt(groupPosition));
}
public int getGroupCount() {
return _shiftMonths.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.month_list_view_item, null);
}
TextView title = (TextView) convertView.findViewById(R.id.monthTitle);
title.setText("" + _shiftMonths.keyAt(groupPosition));
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void forceReload() {
notifyDataSetChanged();
}
}
ShiftListItem:
Code:
public class ShiftListItem extends LinearLayout {
private Salary salary;
private TextView itemTimeAndDate;
private TextView itemCashView;
public ShiftListItem(Context context, AttributeSet attrs) {
super(context, attrs);
salary = new Salary();
}
[user=439709]@override[/user]
protected void onFinishInflate() {
super.onFinishInflate();
itemTimeAndDate = (TextView) findViewById(R.id.itemTimeAndDate);
itemCashView = (TextView) findViewById(R.id.itemCashView);
}
public void setSalary(Salary salary) {
this.salary = salary;
Calendar start = salary.getShiftTime().getStart();
Calendar end = salary.getShiftTime().getEnd();
int tHour;
int tMinute;
int tSec;
tSec = salary.getShiftTime().getDifference(
salary.getShiftTime().getStart(),
salary.getShiftTime().getEnd());
tHour = tSec / 3600;
tSec -= tHour * 3600;
tMinute = tSec / 60;
tSec -= tMinute * 60;
itemTimeAndDate.setText("Time: (Start) "
+ returnTwoDigitString(start.get(Calendar.HOUR_OF_DAY)) + ":"
+ returnTwoDigitString(start.get(Calendar.MINUTE)) + " (End)"
+ returnTwoDigitString(end.get(Calendar.HOUR_OF_DAY)) + ":"
+ returnTwoDigitString(end.get(Calendar.MINUTE)) + "\n"
+ (start.get(Calendar.DAY_OF_MONTH)) + "-"
+ (end.get(Calendar.DAY_OF_MONTH)) + "/"
+ (start.get(Calendar.MONTH) + 1) + "-"
+ (end.get(Calendar.MONTH) + 1) + "/"
+ start.get(Calendar.YEAR) + "-" + end.get(Calendar.YEAR));
itemCashView.setText(salary.getCash() + " " + salary.getCurrency()
+ " Total Time Of: " + returnTwoDigitString(tHour) + ":"
+ returnTwoDigitString(tMinute) + ":"
+ returnTwoDigitString(tSec));
}
public Salary getSalary() {
return salary;
}
private String returnTwoDigitString(int time) {
if (time < 10) {
return "0" + time;
}
return "" + time;
}
}
shift_list_item.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<com...ShiftListItem xmlns:android="....."
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/itemTimeAndDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false" />
<TextView
android:id="@+id/itemCashView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textIsSelectable="false" />
</com.....ShiftListItem>

Adding custom apps to an app switcher panel

I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you

SharedPreferences Context Issue

I have created a questionnaire in the beginning of the app in order to base a user model off the answers chosen. The values of the chosen options are stored as Shared Preferences as shown below. With the data retrieved I am then trying to tag a Google map with certain tags based on the answers chosen. The issue I am encountering is that of reading the stored Shared Preference values across the different activities, from the Question2 Activity, to that of the Map Activity (code below). Any pointers on how to solve the *context* conflict would be greatly appreciated.
Question2 Activity:
Code:
public class Question2 extends Activity{
RadioButton q2a1,q2a2,q2a3;
Button btn2;
public static final String MY_PREF = "MyPreferences";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.activity_question2, null);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
q2a1 = (RadioButton) findViewById(R.id.q2a1);
q2a2 = (RadioButton) findViewById(R.id.q2a2);
q2a3 = (RadioButton) findViewById(R.id.q2a3);
btn2 = (Button) findViewById(R.id.q2_button);
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
SharedPreferences prefernces = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = prefernces.edit();
if (q2a1.isChecked()){
editor.putInt("answer_value2", 1);
editor.commit();
}
if (q2a2.isChecked()){
editor.putInt("answer_value2", 2);
editor.commit();
}
if (q2a3.isChecked()){
editor.putInt("answer_value2", 3);
editor.commit();
}else {
editor.putInt("answer_value2", 0);
editor.commit();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), Question3.class);
startActivity(intent);
}
});
}
}
Map Activity:
Code:
public class MapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLayout)).getMap();
map.setMyLocationEnabled(true);
SharedPreferences preferences = getSharedPreferences(Question2.MY_PREF,MODE_PRIVATE);
int q1answer = preferences.getInt("answer_value", 0);
int q2answer = preferences.getInt("answer_value2", 0);
int q3answer = preferences.getInt("answer_value3", 0);
if(q1answer == 1){
//method
}
if(q1answer == 2){
//method
}
if(q1answer == 3){
//method
}
if(q2answer == 1){
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(HEALTHSHOP).title("Health Shop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grasy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MINT).title("Mint").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 2){
Toast.makeText(getApplicationContext(), "Your result is " + q2answer, Toast.LENGTH_SHORT).show();
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(JUBILEE).title("Jubilee").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grassy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 3){
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(PASTIZZERIA).title("Pastizerria").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(BURGERKING).title("Burger King").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
if(q3answer == 1){
//implementation
}if(q3answer == 2){
//implementation
}if(q3answer == 3){
//implementation
}if(q3answer == 4){
//implementation
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
Use this
create this class in your package
Code:
public class SharedPrefence{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferences";
// Answers (make variable public to access from outside)
public static final String KEY_ANSWER_TWO = "answer_value2";
//similarly other answers tag can be added(this is the key of preference)
// Constructor
public SharedPrefence(Context context) {
_context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create Answer.
* */
public void createAnswer(int ans) {
// Storing name in pref
editor.putInt(KEY_ANSWER_TWO, ans);
// commit changes
editor.commit();
}
public int getAnswer(String tag,int default) {
return pref.getString(tag, default);
}
}
now create an activity and initialise this class in the starting with the activity context.
next call the create answer method of this class and you are done.
also no need to create sharedprefence in each activity.
and it's even better if you create only one activity and use ViewPager for all questions.you can google for it.
And if this was useful click on thanks below.
:victory::victory::victory::victory:

[Q] GP Services achievements unlock and leaderboards uploadnot working

Hello, I have my new game which will be released at the end of february. But now, I have just the signed version installed on phone and the app is not published yet. And hen I try to submit my score to leaderboard, it simply won't and I don't know why. I am using the instance on GoogleApiClient because I need to unlock Achievements in several different Activities. So, here is my code:
Code:
public class GameOverActivity extends GoogleBaseGameActivity {
int coins2;
int score;
int coins;
String type;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_over_layout);
SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
coins2 = shop.getInt("money", 0);
score = getIntent().getExtras().getInt("score");
coins = getIntent().getExtras().getInt("coins");
type = getIntent().getExtras().getString("GameType");
TextView money = (TextView) findViewById(R.id.coins);
money.setText("Coins:" + String.valueOf(coins2) + "+" + String.valueOf(coins));
SharedPreferences.Editor editor = shop.edit();
editor.putInt("money", coins + coins2);
editor.commit();
GoogleApiClient mGoogleApiClient = getApiClient();
mGoogleApiClient.connect();
TextView score1 = (TextView) findViewById(R.id.score);
score1.setText("Score:" + String.valueOf(score));
Button mainMenu = (Button) findViewById(R.id.MainMenu);
if (mGoogleApiClient.isConnected()) {
Games.Achievements.unlockImmediate(mGoogleApiClient, getString(R.string.achievement_newbie_player));
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_casual_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_addicted_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_addicted), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_maniac), 1);
switch (type) {
case "normal":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_normal_mode),
score);
case "hard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_hard_mode),
score);
case "reversed":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_mode),
score);
if(score==69){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_reversed_reversed));
}
case "revHard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_hard_mode),
score);
}
}
mainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
});
Button replay = (Button) findViewById(R.id.replay);
replay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (type.equals("normal")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTap.class);
startActivity(intent);
} else if (type.equals("hard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapHardMode.class);
startActivity(intent);
} else if (type.equals("reversed")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedMode.class);
startActivity(intent);
} else if (type.equals("revHard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedHardMode.class);
startActivity(intent);
} else {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
return false;
return false;
}
@Override
public void onSignInFailed() {
}
@Override
public void onSignInSucceeded() {
}
}
How to make it working ?
The problem is that I can open up the screen with the achievements/leaderboards but can't update them.

[Q] Button MaskFilter?

Hi,
I'm trying to apply a Mask or Blur Filter to some buttons at runtime... This button is reflecting a "layer" object, so I'd like to blur its edges to reflect how transparent is this layer...
I'm able to set a ColorFilter, or apply a maskFIlter to its TextView, but cant figure how to apply a maskFilter to the whole button...
here is the part of my code where I'd like to apply this filter (in a applyFilter method):
Code:
public void createList(LinearLayout lm) {
lm.removeAllViews();
for (int i = 0; i < kwang07Android.nblayers; i++) {
final Button newbtn = new Button(this, null, android.R.attr.buttonStyleSmall);
int col = kwang07Android.layers[i].col;
int newColor = Color.argb(156+(int)(kwang07Android.layers[i].opacite*100), Color.red(col), Color.green(col), Color.blue(col));
newbtn.getBackground().setColorFilter(newColor, MULTIPLY);
[COLOR="DarkOrange"]//applyFilter(newbtn, i, BlurMaskFilter.Blur.INNER);[/COLOR]
newbtn.setText("couche " + Integer.toString(i));
newbtn.setId(i);
newbtn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,30+kwang07Android.layers[i].thickness/20));
final int finalI = i;
newbtn.setOnTouchListener(new Button.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
showColorPickerDialogDemo(newbtn, finalI);
}
return false;
}
});
lm.addView(newbtn);
}
...
Any advice?
Thanks.

Categories

Resources