Sharing Intent Not working Properly - java

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

Related

How to return a specific method on button click event?

Two buttons should update the value "PACK_LIB" inside "Stickers.java".
When they overwrite the String, the method setDefaultStickerPack() should be restarted.
When clicking on buttons b1 or b2 the value "PACK_LIB" will be overwritten by the value "allstickers" or "teststickers".
How can the button b1 or b2 restart the method "if(in==null) "inside setDefaultStickerPack() ?
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "allstickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "teststickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
-------Stickers.java
public static String PACK_LIB ="";
public void setDefaultStickerPack() {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
long packId = 1;
PackData packData = new PackData();
packData.objectId = packId;
packData.name = "ROKOmoji";
packData.iconOn = copyImgFile(in, "i" + packId + "_on");
//packData.iconOff = copyImgFile(inOff, "i" + packId + "_off");
List<StickerData> stickerData = new ArrayList<StickerData>();
long i = 0;
for (String img: packList) {
if(PACK_ICON.equals(img)){
continue;
}
InputStream sIs = null;
try {
sIs = lContext.getAssets().open(curAssets+"/"+img);
} catch (IOException e) {
e.printStackTrace();
}
if (sIs != null) {
StickerData sd = new StickerData();
i=i+1;
File file = copyImgFile(sIs, "s" + img);
sd.objectId = i;
sd.imageId = i;
sd.packId = packId;
sd.packName = packData.name;
sd.file = file;
sd.iconKey = createIconKey(file, "si" + img);
sd.mime = getMimeTypeOfFile(file.getPath());//"image/gif"
sd.url = null;
stickerData.add(sd);
}
}
packData.stickers = stickerData;
packDataListDefault.add(packData);
}
}
U can call the method with parameter. try with this.
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("allstickers");
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("teststickers");
showStickers();
}
});
-------Stickers.java
private static String PACK_LIB ="";
public void setDefaultStickerPack(String packLibValue) {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
PACK_LIB = packLibValue
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
..........
..........
}

fill my button from right to left when I change my language to persian

In my project , I want to play the sound and user must guess the sound.
every thing works well.
I have grid that show some letters and user must selected correct letters to make the right word.
when user selected letters my button fill from left to right
my language is persian and filling my button must be from right to left.
here is my code but don't know where I do this change.
public class TheGame extends Activity {
// Variables
// InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "الف", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ",
"د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ",
"ف", "ق", "ک", "گ" ,"ل","م","ن","و","ه","ی"};
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
SoundPool soundPool;
Context mContext;
String SoundFile,Ribbon;
TextView txt_ribon;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean loaded = false,isLast=false;
private int soundID,Count=0;
StringBuilder sb;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
Button button = (Button)findViewById(R.id.button8);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.rippleanimset);
animation.setFillAfter(false);
animation.setRepeatCount(0x186a0);
button.startAnimation(animation);
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
if(!isLast)
{
int sound_id = mContext.getResources().getIdentifier(SoundFile, "raw",
mContext.getPackageName());
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
}
});
soundID = soundPool.load(this, sound_id, 1);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
((Button)findViewById(R.id.button7)).setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View view)
{
Count+=1;
if (Count %2==1) {
if(loaded)
{
soundPool.play(soundID, 1.0F, 1.0F, 0, 0, 1.0F);
}
else
{
Toast.makeText(getApplicationContext(), "Wait Sound is Loaded", Toast.LENGTH_SHORT).show();
}
}
if (Count % 2==0) {
soundPool.stop(soundID);
soundPool.play(soundID, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
});
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
soundPool.release();
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x]);
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord +=word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
SoundFile=level.getMusicId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
here I CREATE place to fill by selected letter by user:
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
and here i check the letters to fill:
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord +=word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
now it works but my button fill from left to right
I want to fill right to left
Try adding android:supportsRtl="true" in <application> in your AndroidManifest.xml, and then android:layoutDirection="rtl" in your root layout.
Using a check if the language is right to left from this answer, I would structure your code like this:
private static boolean isRTL() {
final int directionality = Character.getDirectionality(Locale.getDefault().getDisplayName().charAt(0));
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}
private void populateButtons(int i, Button word_btn) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
if(isRTL()) {
for(int j = length - 1; j >= 0; j--) {
populateButtons(j, word_btn);
}
} else {}
for (int k = 0; k < length; k++) {
populateButtons(k, word_btn)
}
}
After 2 days, I found the solution. It was easy as a piece of cake.
I dont know why I make it so compilacated.
I just change the my if clause like this:
for (int i = length -1; i >= 0; i--) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}

how to cancel method of count down timer to stop working

I have list of music that user set time to play. I want to have a button to cancel m count down timer .
I test some way but it doesn't work at all.
here is my code to play and set time to play.
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = new HashMap<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info int'o it
textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),null);
//notify about the data change
notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
make the count down timer an instance variable;
private CountDownTimer timer;
then delegate your count to this variable:
#Override
public void onClick(View v) {
...
timer = new CountDownTimer(result, 1000) {
...
}
}
now you can stop the timer whenever you want to:
timer.cancel();
Check this code, working Successfull
call class from here
timer = new CounterClass(timeInmilles, 1000);
timer.start();
CounterClass is here
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}
}
use to cancel see below line
timer.cancel()

Countdown timer, points and incorrect multiplying

I have this code as a method:
String resultTimeString = ct.toString()
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = resultTime1 + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
The problem is in counting. Final score ("punkty") isn't multiply punkty and resultTime and I don't know why. Variable punkty is define as a points from giving a good answer.
Timer count down from 60 to 0.
You have said that the final score always remains 0.
The only way this could be happening is when you have initialized punkty as 0.
Each time, it multiplies by 0, and remains 0.
You should initialize punkty as 1. Then your code will work.
#Hackerdarshi, maybe I will show You all code:
public class QuestionActivity extends Activity {
private static final String TAG = "suemar";
int position = 0;
Button buttonA;
Button buttonB;
Button buttonC;
Button buttonD;
TextView textView;
TextView count;
Retrofit retrofit;
QuestionService questionService;
Call<pytania> QACall;
pytania questionsAnswers;
int licz = 0, punkty = 0;
String id;
char resultTime1ASCII,resultTime2ASCII;
int resultTime=0, resultTime1=0, resultTime2=0;
CountDownTimer ct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
buttonA = (Button) findViewById(R.id.buttonA);
buttonB = (Button) findViewById(R.id.buttonB);
buttonC = (Button) findViewById(R.id.buttonC);
buttonD = (Button) findViewById(R.id.buttonD);
textView = (TextView) findViewById(R.id.textView_pytanie);
count = (TextView) findViewById(R.id.countText);
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
ct = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
String v = String.format("%02d", millisUntilFinished/60000);
int va = (int)( (millisUntilFinished%60000)/1000);
count.setText(String.format("%02d", va));
}
public void onFinish() {
count.setText("0");
koniec();
}
};
ct.start();
Intent intent = getIntent();
position = intent.getExtras().getInt("position");
position++;
id = Integer.toString(position);
//Retrofit magic part
retrofit = new Retrofit.Builder()
.baseUrl("http://46.101.128.24/")
.addConverterFactory(GsonConverterFactory.create())
.build();
questionService = retrofit.create(QuestionService.class);
QACall = questionService.getQuestionsAnswers(id);
QACall.enqueue(new Callback<pytania>() {
#Override
public void onResponse(Call<pytania> call, Response<pytania> response) {
if (response.isSuccessful()) {
questionsAnswers = response.body();
// textView.setText(Integer.toString(questionsAnswers.success));
giveQuestions();
for (Questions c : questionsAnswers.Questions) {
Log.i(TAG, String.format("%s: %s", c.question, c.answer1));
Log.i(TAG, "---------");
}
} else {
Toast.makeText(QuestionActivity.this, "LOL2", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<pytania> call, Throwable t) {
Log.d("Coś się zepsuło", t.getMessage());
Toast.makeText(QuestionActivity.this, "LOL", Toast.LENGTH_SHORT).show();
}
});
}
public void onAnswer(View view) {
licz++;
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
switch (view.getId()) {
case R.id.buttonA:
buttonA.setBackgroundResource(R.drawable.button_game_click);
if (buttonA.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonB:
buttonB.setBackgroundResource(R.drawable.button_game_click);
if (buttonB.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonC:
buttonC.setBackgroundResource(R.drawable.button_game_click);
if (buttonC.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonD:
buttonD.setBackgroundResource(R.drawable.button_game_click);
if (buttonD.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
}
if (licz == 5) {
koniec();
} else {
Runnable r = new Runnable() {
#Override
public void run() {
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
giveQuestions();
}
};
Handler h = new Handler();
h.postDelayed(r, 300);
}
}
private void koniec() {
String resultTimeString = ct.toString();
//resultTime1ASCII = resultTimeString.charAt(resultTimeString.length() - 2);
//resultTime2ASCII = resultTimeString.charAt(resultTimeString.length()-1);
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = (resultTime1*10) + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
Intent intent = new Intent(QuestionActivity.this, YourResultActivity.class);
startActivity(intent);
finish();
}
public void giveQuestions() {
questionsAnswers.Questions.get(licz).ShuffleAnswers();
textView.setText(questionsAnswers.Questions.get(licz).question);
buttonA.setText(questionsAnswers.Questions.get(licz).getAnswer(0));
buttonB.setText(questionsAnswers.Questions.get(licz).getAnswer(1));
buttonC.setText(questionsAnswers.Questions.get(licz).getAnswer(2));
buttonD.setText(questionsAnswers.Questions.get(licz).getAnswer(3));
}
}

Paypal with invoice and order confirmation in android app

I have to develop one shopping cart app and integrate Paypal. How can I set the Paypal payment invoice data?
How can I add productname, quantity, price to Paypal payment invoice?.
This is my code for product that is added to cart page:
public class SingleMenuItem extends Activity {
static final String KEY_TITLE = "Name";
static final String KEY_COST = "Price";
static final String KEY_TOTAL = "total";
static final String KEY_QTY = "qty";
static final String KEY_THUMB_URL = "Image";
private EditText edit_qty_code;
private TextView txt_total;
private TextView text_cost_code;
private double itemamount = 0;
private double itemquantity = 0;
String mTitle, mQty, mCost, mTotal;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
Intent in = getIntent();
String title = in.getStringExtra(KEY_TITLE);
String thumb_url = in.getStringExtra(KEY_THUMB_URL);
String cost = in.getStringExtra(KEY_COST);
String total = in.getStringExtra(KEY_TOTAL);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView imgv = (ImageView) findViewById(R.id.single_thumb);
final TextView txttitle = (TextView) findViewById(R.id.single_title);
TextView txtheader = (TextView) findViewById(R.id.actionbar);
text_cost_code = (TextView) findViewById(R.id.single_cost);
edit_qty_code = (EditText) findViewById(R.id.single_qty);
edit_qty_code.setText("1");
txt_total = (TextView) findViewById(R.id.single_total);
txttitle.setText(title);
txtheader.setText(title);
text_cost_code.setText(cost);
txt_total.setText(total);
imageLoader.DisplayImage(thumb_url, imgv);
itemamount = Double.parseDouble(text_cost_code.getText().toString());
txt_total.setText(Double.toString(itemamount));
edit_qty_code.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
if (!edit_qty_code.getText().toString().equals("")
|| !edit_qty_code.getText().toString().equals("")) {
itemquantity = Double.parseDouble(edit_qty_code.getText()
.toString());
itemamount = Double.parseDouble(text_cost_code.getText()
.toString());
txt_total.setText(Double
.toString(itemquantity * itemamount));
} else {
txt_total.setText("0.00");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
ImageButton mImgAddCart = (ImageButton) findViewById(R.id.img_add);
mImgAddCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mTitle = txttitle.getText().toString();
mCost = text_cost_code.getText().toString();
mCost = mCost.replace("From ", "");
mTotal = txt_total.getText().toString();
mTotal = mTotal.replace("From ", "");
mQty = edit_qty_code.getText().toString();
if (Constants.mItem_Detail.size() <= 0) {
HashMap<String, String> mTempObj = new HashMap<String, String>();
mTempObj.put(KEY_TITLE, mTitle);
mTempObj.put(KEY_QTY, mQty);
mTempObj.put(KEY_COST, mCost);
mTempObj.put(KEY_TOTAL, mTotal);
Constants.mItem_Detail.add(mTempObj);
} else {
for (int i = 0; i < Constants.mItem_Detail.size(); i++) {
if (Constants.mItem_Detail.get(i).get(KEY_TITLE)
.equals(mTitle)) {
Constants.mItem_Detail.remove(i);
break;
} else {
}
}
HashMap<String, String> mTempObj = new HashMap<String, String>();
mTempObj.put(KEY_TITLE, mTitle);
mTempObj.put(KEY_QTY, mQty);
mTempObj.put(KEY_COST, mCost);
mTempObj.put(KEY_TOTAL, mTotal);
Constants.mItem_Detail.add(mTempObj);
}
AlertDialog.Builder alertdialog = new AlertDialog.Builder(
SingleMenuItem.this);
alertdialog.setTitle(getResources()
.getString(R.string.app_name));
alertdialog.setMessage("Add in ViewCart");
alertdialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
//finish();
return;
}
});
alertdialog.show();
}
});
ImageButton mImgViewCart = (ImageButton) findViewById(R.id.img_view);
mImgViewCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mInViewCart = new Intent(SingleMenuItem.this,
ViewCartActivity.class);
startActivity(mInViewCart);
}
});
This is code for product is added to cart:
ListView mLstView1 = (ListView) findViewById(R.id.listView1);
TextView mTxtViewGrandTotal = (TextView) findViewById(R.id.mTxtViewGrandTotalValue);
Button mBtnSubmit = (Button) findViewById(R.id.mBtnSubmit);
ViewCartAdapter mViewCartAdpt = new ViewCartAdapter(
ViewCartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
if (Constants.mItem_Detail.size() > 0) {
Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0)
.get(SingleMenuItem.KEY_TOTAL));
for (int i = 1; i < Constants.mItem_Detail.size(); i++) {
mGTotal = mGTotal
+ Double.parseDouble(Constants.mItem_Detail.get(i).get(
SingleMenuItem.KEY_TOTAL));
}
mGrandTotal = String.valueOf(mGTotal);
mTxtViewGrandTotal.setText("$" + mGrandTotal);
}
mBtnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), CustomerLogin.class);
startActivity(i);
}
});
This is my paypalintegrationactivity:
public class PayPalIntegrationActivity extends Activity implements OnClickListener {
private PayPal mPayPal;
private CheckoutButton launchPayPalButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_pal_integration);
mPayPal=PayPal.initWithAppID(this,Constants.PAYPAL_APP_ID,PayPal.ENV_SANDBOX);
initUI();
}
private void initUI() {
launchPayPalButton = mPayPal.getCheckoutButton(this,
PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener(this);
((RelativeLayout)findViewById(R.id.main_layout)).addView(launchPayPalButton);
}
#Override
public void onClick(View v) {
payWithPaypal();
}
private PayPalPayment payWithPaypal() {
PayPalPayment newPayment = new PayPalPayment();
BigDecimal bigDecimal=new BigDecimal(10);
newPayment.setSubtotal(bigDecimal);
newPayment.setCurrencyType(Currency.getInstance(Locale.US));
newPayment.setRecipient("krishnaveni.veeman#mercuryminds.com");
newPayment.setMerchantName("My Merchant");
newPayment.setSubtotal(new BigDecimal(mTotal));
newPayment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
PayPalInvoiceData invoice = new PayPalInvoiceData();
return newPayment;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode) {
case Activity.RESULT_OK:
String payKey =
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Toast.makeText(this,"Payment Successful",Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(this,"Payment Cancel",Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(this,"Payment Failed",Toast.LENGTH_LONG).show();
String errorID =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
String errorMessage =
data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
break;
}
Here how can i add productname to paypalpayment invoice.please help me.
you can add paypalinvoice object to your project, then you can add details to that invoice,
try this code
PayPalInvoiceItem item1 = new PayPalInvoiceItem();
item1.setName("Pink Stuffed Bunny");
item1.setTotalPrice(new BigDecimal("6.00"));
item1.setQuantity(3);
invoice.getInvoiceItems().add(item1);
hope it will help to you.

Categories

Resources