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.
Related
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]));
}
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
i am adding data to list view it shows multiple Times .
I have two Activities.first activity i have add button and listview . when i click add button i goes to second activity.in second activity,adding data to ArrayList.here i am passing arraylist object to first Activity using parcelable .
in first activity,here i am storing the getting ArrayList object values in one Arraylist<>.and then passing object to listview. in listview data showing in multipule times .please go though this link https://www.codota.com/codebox/#/9lqy1ardnfyctyb9/shared
please, sorry i am not good in english.
public class MainActivity extends ActionBarActivity {
ImageView addView, searchView;
DetailsEmp detailsEmp = new DetailsEmp();
ListView listView;
ArrayList<Employee> listDetails=new ArrayList<Employee>();
DetailsAdapter detailsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Employee emp = (Employee) getIntent().getParcelableExtra(detailsEmp.PAR_KEY);
listView = (ListView) findViewById(R.id.listView);
addView = (ImageView) findViewById(R.id.addImage);
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
if (emp != null) {
Employee emplyoee=new Employee();
{
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Log.d("bundle Size is ", "Emp Name is " + emp.getName());
Log.d("bundle Size is ", "Emp Sex is " + emp.getListGen());
Log.d("list Size is ", " ArrayList<Emplyoee> " + listDetails.size());
for (int i = 0; i < listDetails.size(); i++) {
Log.d("list Size is ", " ArrayList<Emplyoee> "
+ listDetails.get(i).getName().toString());
}
}
detailsAdapter=new DetailsAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, listDetails);
listView.setAdapter(detailsAdapter);
}
}
#Override
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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
// second activity
public class DetailsAdapter extends ArrayAdapter<Employee> {
private Context context;
private ArrayList<Employee> listDetails;
public DetailsAdapter(Context context, int resource,
ArrayList<Employee> listDetails) {
super(context, resource, listDetails);
// TODO Auto-generated constructor stub
this.context = context;
this.listDetails = listDetails;
}
private class ViewHolder
{
TextView empName,empCmpny,empDisig,empAge,empExp ;
ImageView empIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder=null;
Employee emplyoee=getItem(position);
LayoutInflater inflator=(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
convertView =inflator.inflate(R.layout.activity_listview, parent, false);
holder=new ViewHolder();
holder.empName=(TextView)convertView.findViewById(R.id.listName);
holder.empCmpny=(TextView)convertView.findViewById(R.id.listCmpny);
holder.empDisig=(TextView)convertView.findViewById(R.id.listDesignation);
holder.empIcon=(ImageView)convertView.findViewById(R.id.female);
convertView.setTag(holder);
}
holder=(ViewHolder)convertView.getTag();
for (int j = 0; j < listDetails.size(); j++) {
holder.empName.setText(emplyoee.getName());
holder.empCmpny.setText(emplyoee.getCmpny());
holder.empDisig.setText(emplyoee.getDisig());
if (emplyoee.getListGen().toString() == "Male") {
holder.empIcon.setImageResource(R.drawable.client_male_dark);
}
}
return convertView;
}
}
// POJO class
public class Employee implements Parcelable {
String listName = null;
String listCmpny = null;
String listDisig = null;
String listExp = null;
String listAge = null;
String listGen = null;
public String getName() {
return listName;
}
public String getListExp() {
return listExp;
}
public void setListExp(String listExp) {
this.listExp = listExp;
}
public String getListAge() {
return listAge;
}
public void setListAge(String listAge) {
this.listAge = listAge;
}
public String getListGen() {
return listGen;
}
public void setListGen(String listGen) {
this.listGen = listGen;
}
public void setName(String listName) {
this.listName = listName;
}
public String getCmpny() {
return listCmpny;
}
public void setCmpny(String listCmpny) {
this.listCmpny = listCmpny;
}
public String getDisig() {
return listDisig;
}
public void setDisig(String listDisig) {
this.listDisig = listDisig;
}
public static final Parcelable.Creator CREATOR = new Creator() {
#Override
public Employee createFromParcel(Parcel source) {
Employee emp = new Employee();
emp.listName = source.readString();
emp.listCmpny = source.readString();
emp.listDisig = source.readString();
emp.listAge = source.readString();
emp.listGen = source.readString();
emp.listExp = source.readString();
return emp;
}
public Employee[] newArray(int size) {
return new Employee[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(listName);
dest.writeString(listCmpny);
dest.writeString(listDisig);
dest.writeString(listAge);
dest.writeString(listGen);
dest.writeString(listExp);
}
}
// DetailsEmp
public class DetailsEmp extends Activity {
public final static String PAR_KEY="key_par";
private EditText empName, empCmpny, empDisig, empAge, empExp;
private RadioGroup empGender;
private RadioButton empMale, empFemale;
Button save;
ArrayList<Employee> list = new ArrayList<Employee>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_emp);
// getting the details from the xml
empName = (EditText) findViewById(R.id.editName);
empCmpny = (EditText) findViewById(R.id.editCmpny);
empDisig = (EditText) findViewById(R.id.editDisignation);
empAge = (EditText) findViewById(R.id.editAge);
empExp = (EditText) findViewById(R.id.editExp);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
empGenderDetails();
}
});
}
protected void empGenderDetails() {
// TODO Auto-generated method stub
// empMale = (RadioButton) findViewById(R.id.male);
Employee emp = new Employee();
emp.setName(empName.getText().toString());
//list.add(emp);
emp.setCmpny(empCmpny.getText().toString());
//list.add(emp);
emp.setDisig(empDisig.getText().toString());
//list.add(emp);
emp.setListAge(empAge.getText().toString());
//list.add(emp);
emp.setListExp(empExp.getText().toString());
//list.add(emp);
empFemale = (RadioButton) findViewById(R.id.female);
empGender = (RadioGroup) findViewById(R.id.radioGroup);
int sel = empGender.getCheckedRadioButtonId();
empMale = (RadioButton) findViewById(sel);
emp.setListGen(empMale.getText().toString());
Log.d("Employee data ", " Emp " + emp.listName.toString()
+ empMale.getText().toString()
+ empExp.getText().toString());
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
Bundle b=new Bundle();
b.putParcelable(PAR_KEY , emp);
i.putExtras(b);
//setResult(RESULT_OK, i);
startActivity(i);
finish();
//list.add(emp);
Log.d("Emplyooe Size ","Emplyoee " + emp.getName());
/*
}
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
you keep adding a new emplyoee (mispelled btw, but that's up to you), you need to do
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
or:
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
Your way of using Adapter is quite a immature one. Please On click of the save button add your "emp" object to the ArrayList and don't recreate the adapter once again when your dataset is changed just notify it the data has changed. Have a method as given below in your adapter rather then having the data supply in the constructor.
public void setData(ArrayList<Employee> _listOfEmp){
this.listOfEmp = _listOfEmp;
}
and then notify the adapter in your activity when ever you change the dataset.
For your clarity.
Read this:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
and see this example:
http://www.vogella.com/tutorials/AndroidListView/article.html
I am new to Android programming and I'm working on a project that fetches data from MySQL DB.
Now, I have two java files. The first fetches employees and their id, it has Spinners that when clicked, it copies the value of the name and id of the employees to the TextViews and transfer the data to the next Activity through Intent.
While the second fetches employees' schedule based on the employee id. This second activity should populate Spinner based on the id of the employees that was passes from the first activity.
First Activity:
public class FirstActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > aestheticianList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_aesthetician);
new DownloadJSON().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersAestheticianActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("full_name", full_name);
i.putExtra("aid", aid);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
txtService_name.setText(service_name);
txtPrice.setText(price);
}
private class DownloadJSON extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
aestheticianList = new ArrayList < String > ();
try {
jObj = JSONParser.getJSONfromURL("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_aesthetician2.php");
try {
jArray = jObj.getJSONArray("aesthetician");
for (int i = 0; i < jArray.length(); i++) {
jObj = jArray.getJSONObject(i);
Items item = new Items();
item.setFull_name(jObj.optString("full_name"));
item.setAid(jObj.optString("aid"));
items.add(item);
aestheticianList.add(jObj.optString("full_name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_aesthetician);
spin.setAdapter(new ArrayAdapter < String > (FarmersAestheticianActivity.this,
android.R.layout.simple_spinner_dropdown_item, aestheticianList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_full_name = (TextView) findViewById(R.id.full_name);
TextView txt_aid = (TextView) findViewById(R.id.aid);
txt_full_name.setText(items.get(position).getFull_name());
txt_aid.setText(items.get(position).getAid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
Second Activity:
public class SecondActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > dateTimeList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price, full_name, aid, tid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_datetime);
new DownService().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersConfirmationActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String tid = ((TextView) findViewById(R.id.tid)).getText().toString();
String datetime = ((TextView) findViewById(R.id.datetime)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("aid", aid);
i.putExtra("full_name", full_name);
i.putExtra("tid", tid);
i.putExtra("date_time", datetime);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
TextView txtFull_name = (TextView) findViewById(R.id.full_name);
TextView txtAid = (TextView) findViewById(R.id.aid);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
full_name = i.getStringExtra("full_name");
aid = i.getStringExtra("aid");
txtService_name.setText(service_name);
txtPrice.setText(price);
txtFull_name.setText(full_name);
txtAid.setText(aid);
}
private class DownService extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
dateTimeList = new ArrayList < String > ();
/////////////////////////
List < NameValuePair > param = new ArrayList < NameValuePair > ();
param.add(new BasicNameValuePair("aid", aid));
/////////////////////////
try {
String jObj = JSONParser.makeHttpRequest2("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time2.php", "GET", param); //("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time.php");
try {
JSONObject jsonObj = new JSONObject(jObj);
for (int i = 0; i < jArray.length(); i++) {
jsonObj = jArray.getJSONObject(i);
Items item = new Items();
item.setDateTime(jsonObj.optString("date_time"));
item.setTid(jsonObj.optString("tid"));
items.add(item);
dateTimeList.add(jsonObj.optString("date_time"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_datetime);
spin.setAdapter(new ArrayAdapter < String > (FarmersDateTimeActivity.this,
android.R.layout.simple_spinner_dropdown_item, dateTimeList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_datetime = (TextView) findViewById(R.id.datetime);
TextView txt_tid = (TextView) findViewById(R.id.tid);
txt_datetime.setText(items.get(position).getDateTime());
txt_tid.setText(items.get(position).getTid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
in second Activity:
Bundle extras = getIntent().getExtras();
int id = extras.getInt("Id"); // get the id passed from first activty
I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);