how to pass array value to next activity - android

i want to pass all the array values to next activity .but i dont know how to do that
how to use arrayList to implement this .
i have done this coding but it give me an error when i click on the button
i closed applicaton forcefully
package com.example.snooder;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
public class players extends Activity {
LinearLayout player_layout;
Bundle b;
List<EditText> allEds = new ArrayList<EditText>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.players);
b = getIntent().getExtras();
String resStr = b.getString("name");
player_layout = (LinearLayout) findViewById(R.id.player_layout);
EditText[] ed1 = new EditText[Integer.parseInt(resStr)+1];
Button add_player = new Button(players.this);
add_player.setText("Add Players");
for(int i=1;i<=Integer.parseInt(resStr);i++)
{
ed1[i] = new EditText(players.this);
allEds.add(ed1[i]);
player_layout.addView(ed1[i]);
ed1[i].setId(i);
ed1[i].setHint("enter player" +i+ "name");
ed1[i].setHeight(50);
ed1[i].setWidth(300);
add_player.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(players.this,player_name.class);
String[] strings = new String[allEds.size()];
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
}
for(int i=0;i<allEds.size();i++)
{
intent.putExtra("playerName",strings[i].toString());
}
startActivity(intent);
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_layout.addView(add_player, lp);
}
}

The error happens here:
intent.putExtra("playerName",strings[i].toString());
At this point, the array strings is still empty; you are trying to reference null values.
With regards to your question, however, you got the proper method: put the values in the intent that will be sent to the next activity. You can use putExtra that takes a String array as shown on this SO question.

You are adding all extras with same name in the end it is going to be just one.
There is overloaded version of putExtra for array of strings

Related

Passing data always comes back 0

I have fixed the problem that I originally create this question for, but now I have a new problem. The activity gets created and it goes to my other screen when I select the button, but now the value that is suppose to get passed to the second activity always comes back as 0.
I am assuming this is the line that is causing it? How, would I fix that?
int goal = intent.getIntExtra("calorieGoal", 0);
My Main Activity.java
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
String selection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//gets data from the user input
final EditText weight = (EditText)findViewById(R.id.bodyWeight);
final EditText age = (EditText)findViewById(R.id.yearsOld);
final EditText height = (EditText)findViewById(R.id.inchHeight);
//gets the spinner selection
final Spinner activityLevel = (Spinner)findViewById(R.id.activityLevel);
//initate the button, and set code for when the button is clicked
Button lose = (Button)findViewById(R.id.loseButton);
lose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userWeight = weight.getText().toString();
String userheight = height.getText().toString();
String userAge = age.getText().toString();
int uWeight = Integer.parseInt(userWeight);
int uHeight = Integer.parseInt(userheight);
int uAge = Integer.parseInt(userAge);
double calorieGoal;
selection = activityLevel.getSelectedItem().toString();
if(selection == "sedentary"){
double bmr = 66.47 + (6.24 * uWeight) + (12.7 * uHeight) - (6.75 * uAge);
calorieGoal = bmr * 1.2;
Intent intent = new Intent(MainActivity.this, Gain_Activity.class);
intent.putExtra("calorieGoal", calorieGoal);
startActivity(intent);
}
}
});
}
}
second activity that I am trying to send the data to
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Gain_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gain_);
Intent intent = getIntent();
int goal = intent.getIntExtra("calorieGoal", 0);
TextView texview = findViewById(R.id.calorieGoal);
texview.setText(goal);
}
}
calorieGoal is of type double, not int. You will not be able to get it via getIntExtra.
Try getDoubleExtra.

Column chart with sqllite Db values based on Spinner value chnage?

I am very new to this API.I have knowledge on doing samples with this API.after that my requirement is display the Column graph based on Spinner Values selection .the query table data is coming correctly the problem is not appending the latest values to the chart .
In My App i have one spinner name it as Customer Name:
when i change the spinner-value i am sending the Customer name to input parameter to sqllite and display the graph for that i write the following code.
package com.appulento.salestracking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import com.appulento.salestrackingdb.DBAdapter;
import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartAxis;
import com.artfulbits.aiCharts.Base.ChartCollection;
import com.artfulbits.aiCharts.Base.ChartCollection.IChangeListener;
import com.artfulbits.aiCharts.Base.ChartNamedCollection;
import com.artfulbits.aiCharts.Base.ChartPalette;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Types.ChartTypes;
public class SalesTrackingByCustomer extends Activity {
private DBAdapter db;
private Spinner spinner1, spinner2;
private String[] prodctnames;
private String[] prodctnames1;
private double[] product_1;
private double[] product_2;
public int count;
public String custid;
public Sample customerdetails;
public ChartCollection<String> collection;
ChartArea area;
ChartArea area1;
private SimpleAdapter mSchedule;
Vector<String> vec_custid=new Vector<String>();
Vector<String> vec_oldno=new Vector<String>();
Vector<String> vec_productid=new Vector<String>();
Vector<String> vec_qty=new Vector<String>();
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bycustomers);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mListView=(ListView)findViewById(R.id.listView1);
prodctnames=new String[10];
product_1=new double[10];
prodctnames1=new String[10];
product_2=new double[10];
db=new DBAdapter(this);
final ChartView chartView = (ChartView) findViewById(R.id.chartView);
ChartPalette palette = new ChartPalette(0xffffd7e8);
chartView.setPalette(palette);
final ChartSeries product1 = new ChartSeries("P1", ChartTypes.Column);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position=spinner1.getSelectedItemPosition();
System.out.println("=====ITEM POSITION======"+position);
final String selected=arg0.getItemAtPosition(arg2).toString();
System.out.println("=====IN SELECTED======"+selected);
//finish();
db.open();
Cursor customer=db.fetchorderCustomername(selected);
custid=customer.getString(0);
System.out.println("=====CUSTOMER NAME ID======"+custid);
Cursor cursor=db.fetchorderDetails(custid);
count=cursor.getCount();
System.out.println("=====COUNT======"+count);
int i=0;
while (i<count)
{
String productid=cursor.getString(1);
prodctnames[i]=productid;
String qty=cursor.getString(2);
product_1[i]=Double.parseDouble(qty);
System.out.println("=====PROID======"+prodctnames[i]+"=====QUANTITY======"+product_1[i]);
cursor.moveToNext();
i++;
}
for (int j = 0; j < count; j++)
{
ChartPoint point = product1.getPoints().addXY(j, product_1[j]);
point.setAxisLabel(prodctnames[j]);
}
if(position==0)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area = chartView.getAreas().get(0);
area.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
if(position==1)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area1 = chartView.getAreas().get(0);
area1.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
//area.refresh();
db.close();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
My problem is at first time Application Launch the graph is Displaying successfully when i change the Spinner value selection the app got closed and display the fallowing exception in my log cat:
java.security.InvalidParameterException: This name already presents at com.artfulbits.aiCharts.Base.ChartNamedCollection.validateName(SourceFile:128 ) at com.artfulbits.aiCharts.Base.ChartNamedCollection.validate
please see once and let me know where i am doing Mistake in my code.The dynamic vlaues is not appending to that chart in the above code.
Thanks in Advance....
The problem is that you're trying to add new area with the same name. I'm not exactly well versed in the API enough, but i'd imagine that the issue comes when you try this line a second time:
chartView.getSeries().add(product1);
I also noticed that you never used the following:
prodctnames1=new String[10];
product_2=new double[10];
If i could make a suggestion, perhaps it isn't best to have all your code in a click listener. maybe you can fill your datasets at the beginning and then only show the graphs upon using the spinner. Because if one clicks the spinner more than once, you have to go to the database to get the same information.

TextToSpeech - Android

I'm working on a simple game. The idea of the first round is that, there are 26 buttons (images) on the first activity - english alphabet and I want to make it pronounce on button click. For example, when I press "a" button, it must say "a". How can I get the ID of each button, then string of it and give it to speak() method as a parameter? THANKS IN ADVANCE !
Code is here:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.Locale;
import java.util.Random;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class FirstActivity extends Activity {
/** Called when the activity is first created. */
TextToSpeech ttx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstact);
ttx = new TextToSpeech(
FirstActivity.this,
new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
ttx.setLanguage(Locale.US);
}
}
});
TableLayout table = (TableLayout) findViewById(R.id.table);
String alphabet = "abcdefghijqlmnopqrstuvwxyz";
int pos = 0;
for (int i = 0; i < 7; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < 4; j++) {
if (pos == 26) {
break;
}
Button but = new Button(this);
/*but.setOnClickListener(btnListener);*/
but.setText(Character.toString(alphabet.charAt(pos++)));
but.setHeight(80);
but.setWidth(70);
but.setBackgroundResource(R.drawable.burti);
row.addView(but);
but.setId(pos);
but.setOnClickListener((OnClickListener) this);
table.addView(row);
}}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(ttx != null){
ttx.stop();
ttx.shutdown();
}
super.onPause();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
String pressed = but.getText().toString(); //error here....
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
}
I made a working example: http://frank.anemaet.nl/android/TalkingButtons.zip
Here is a snippet of the working code:
for (int i = 0; i < alphabet.length(); i++)
{
TableRow row = new TableRow(this);
Button but;
but = new Button(this);
but.setText(Character.toString(alphabet.charAt(i)));
but.setHeight(button_width);
but.setWidth(button_height);
but.setId(i);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
performClick(v);
}
});
row.addView(but);
table.addView(row);
}
...
public void performClick(View arg0){
Button tv = (Button)findViewById(arg0.getId());
String pressed = tv.getText().toString();
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
Your onInit() method has to do more, like handle when the user does not have the language data installed.
See this code for a helper class.

Android PayPal OnClickListener is not working

I am trying to connect the PayPal to my app. Basically my app will have one Scan button and one PayPal Button on the screen. Scan button calls the ZXing library and scan the barcodes. However, I still cannot connect with PayPal button yet because OnClickListener and getApplicationContext() is not working. I have read PayPal documentation , StackOverflow and still couldn't work out. I am wondering what is wrong with my code? Any Suggestions please?Thank you for your help :)
package thet.mon.aye;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalReceiverDetails;
import com.paypal.android.MEP.PayPalPayment;
import android.content.Context;
public class DevilscanActivity extends ListActivity implements onClickListener {
/** Called when the activity is first created. */
private static final int ACTIVITY_CREATE=0;
private BarcodeDBAdapter mDbHelper;
private Cursor mNotesCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbHelper = new BarcodeDBAdapter(this);
mDbHelper.open();
fillData();
PayPal ppObj = PayPal.getInstance();
final Button scanButton = (Button) findViewById(R.id.button);
scanButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent("com.google.zxing.client.android.SCAN");
intent1.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent1, 0);
}
});
CheckoutButton launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener((OnClickListener) this);
((RelativeLayout)findViewById(R.id.RelativeLayout01)).addView(launchPayPalButton);
}
static public PayPal initWithAppID(Context context, String appID, int server)
{
PayPal ppObj;
if (ppObj == null) {
try {
ppObj = PayPal.initWithAppID(getApplicationContext(),"", PayPal.ENV_NONE);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
ppObj.setShippingEnabled(false);
}
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{BarcodeDBAdapter.KEY_BARCODE_TYPE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.barcode_row, mNotesCursor, from, to);
setListAdapter(notes);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent1) {
//intent1 = new Intent("com.google.zxing.client.android.SCAN");
// intent1.putExtra("SCAN_MODE", "QR_CODE_MODE");
// startActivityForResult(intent1, 0);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent1.getStringExtra("SCAN_RESULT");
String format = intent1.getStringExtra("SCAN_RESULT_FORMAT");
mDbHelper.createNote(contents, format);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}

Android Paypal launch button OnClick is executed only once in the activity lifespan

This one is destroying my brain, when you enter the activity you can click the paypal button and you go into the paypal activity fine. If you cancel the paypal activity you are brought back to the original activity. From here if you click the button again nothing happens. I tried printing a basic message to console in the OnClick method and it didn't even show, it doesn't seem to be registering the clicks. I'm Assuming the problem has nothing to do with the layout xml file or the manifest file. I would post an image but i cant because im new, all you need to know is that its a checkout screen with a paypal button really.
Thanks in advance,
Hugh.
package com.cit.datastructuretesting;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalPayment;
public class StoreItemInterface extends Activity implements OnClickListener, OnKeyListener
{
Double subtotal, shipping, total;
EditText etItemQuantity;
TextView tvItemSubtotal, tvItemTotal;
DecimalFormat decFormat = new DecimalFormat("#.##");
PayPal ppObj;
CheckoutButton launchPayPalButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.storeiteminterface);
ImageView ivItemImage = (ImageView) findViewById(R.id.ivItemImage2);
TextView tvItemTitle = (TextView) findViewById(R.id.tvItemTitle2);
TextView tvItemDescription = (TextView) findViewById(R.id.tvItemDescription2);
etItemQuantity = (EditText) findViewById(R.id.etItemQuantity);
tvItemSubtotal = (TextView) findViewById(R.id.tvItemSubtotal);
TextView tvItemShipping = (TextView) findViewById(R.id.tvItemShipping);
tvItemTotal = (TextView) findViewById(R.id.tvItemTotal);
subtotal = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getPrice() * Integer.parseInt(etItemQuantity.getText().toString());
shipping = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getShippingPrice();
total = subtotal + shipping;
ivItemImage.setImageBitmap(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getImageBitmap());
tvItemTitle.setText(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getTitle());
tvItemDescription.setText(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getDescription());
tvItemSubtotal.setText("€" + decFormat.format(subtotal));
tvItemShipping.setText("€" + decFormat.format(shipping));
tvItemTotal.setText("€" + decFormat.format(total));
etItemQuantity.setOnKeyListener(this);
//setup paypal stuff
ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
((RelativeLayout)findViewById(R.id.paypalLayout)).addView(launchPayPalButton);
launchPayPalButton.setOnClickListener(this);
}
#Override
public void onClick(View arg0)
{
if(arg0.getId() == launchPayPalButton.getId())
{
System.out.println("TEST");
if(!tvItemTotal.getText().toString().equals("---"))
{
PayPalPayment newPayment = new PayPalPayment();
newPayment.setSubtotal(BigDecimal.valueOf(total));
newPayment.setCurrencyType("EUR");
newPayment.setRecipient("Cape_1328492032_biz#mycit.ie");
newPayment.setMerchantName("Cape Clear App");
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, StoreItemInterface.this);
StoreItemInterface.this.startActivityForResult(paypalIntent, 1);
}
else
{
Toast.makeText(StoreItemInterface.this, "Invalid Quantity!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2)
{
if(etItemQuantity.getText().toString() != null && !etItemQuantity.getText().toString().trim().equals("") && !etItemQuantity.getText().toString().trim().equals("0"))
{
subtotal = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getPrice() * Integer.parseInt(etItemQuantity.getText().toString());
total = subtotal + shipping;
tvItemSubtotal.setText("€" + subtotal);
tvItemTotal.setText("€" + decFormat.format(total));
}
else
{
tvItemSubtotal.setText("---");
tvItemTotal.setText("---");
}
return false;
}
}
Try launchPayPalButton.updateButton() after the stuff you do when onClick()
https://www.x.com/developers/paypal/forums/paypal-mobile-xspace/android-interrupting-paypal-onclick-event#answer-203333
In case you are still looking for an answer, I have one
If you have a look at getCheckoutButton method, it takes Context as parameter, so when the Activity is for e.g. say Paused which happens when you start another Activity, the instance of the CheckoutButton is lost somehow.
I fixed is by using updateButton method in onResume of the Activity
#Override
protected void onResume() {
/**
* The CheckoutButton has to be updated each time the Activity is
* resumed, otherwise the onClickListener of CheckoutButton will not work
**/
if (mCheckOutBtn != null && (mCheckOutBtn instanceof CheckoutButton))
mCheckOutBtn.updateButton();
super.onResume();
}
This works considering you initialized PayPal library and CheckoutButton in onCreate of Activity.

Categories

Resources