I am building an android application where an user select their favorite stuff.
The name of stuff is added in an array when user clicks on the stuff's image.
Now I want to know how can I parse the value of that array to any fragment and show it in my spinner list.
For example: user select Mobile and tablet by clicking on respective images then these values added in to an array name 'stuffarray' now I want to pass this array to my fragment on an 'submitted' button and when I click on an spinner of my fragment it Should have mobile and tablet value in there list.
Here is my code for stuff selection :
I am building an android application where an user select their favorite stuff.
The name of stuff is added in an array when user clicks on the stuff's image.
Now I want to know how can I parse the value of that array to any fragment and show it in my spinner list.
For example: user select Mobile and tablet by clicking on respective images then these values added in to an array name 'stuffarray' now I want to pass this array to my fragment on an 'submitted' button and when I click on an spinner of my fragment it Should have mobile and tablet value in there list.
Here is my code for stuff selection :
submite = (ImageButton) findViewById(R.id.nextscreen);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent innext = new Intent(getApplicationContext(), MainActivitytabnew.class);
startActivity(innext);
});
img1 = (ImageButton) findViewById(R.id.imageButton1);
img1.setBackgroundResource(R.drawable.mobile);
img1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isClicked1=!isClicked1;
if (isClicked1) {
img1.setImageResource(R.drawable.mobile);
start();
stuff1 = "mobile";
myList.add(stuff1);
}else {
img1.setImageResource(R.drawable.mobile);
myList.remove(sport1);
//sport1 = "";
txt1.setText("");
}
}
});
img2 = (ImageButton) findViewById(R.id.imageButton2);
img2.setBackgroundResource(R.drawable.tablet);
img2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isClicked2=!isClicked2;
if (isClicked2) {
img2.setImageResource(R.drawable.tablet);
start();
stuff2 = "tablet";
myList.add(stuff2);
}else {
img2.setImageResource(R.drawable.tablet);
// sport2 = "";
myList.remove(sport2);
}
}
});
You could also set the value before you open it.
First activity
Intent intent = new Intent( this, YourOtherClass.class );
int[] myArray = { 0, 1, 2, 3 };
YourOtherClass.array = myArray;
startActivity( intent );
Second activity
public static int[] array;
Where this is your activity.
Use putExtra():
int helloworld = 100;
Intent intent = new Intent( this, Class2.class );
intent.putExtra( "myInt", helloworld );
startActivity( intent );
then in your next activity use getExtra()
see documentation for intent.
int passedInt = getIntent().getExtras().getInt( "myInt" );
Related
Hi i have a problem while creating imageview when i click previous(b1) and next(b2) button it shows next and previous images from img array but sometimes it shows random images like android layout images etc.
public class FullTable extends Activity{
int[] img={
R.drawable.t1,R.drawable.t2,R.drawable.t3,
R.drawable.t4,R.drawable.t5,R.drawable.t6,
R.drawable.t7,R.drawable.t8,R.drawable.t9,
R.drawable.t10,R.drawable.t11,R.drawable.t12,
R.drawable.t13,R.drawable.t14,R.drawable.t15,
R.drawable.t16,R.drawable.t17,R.drawable.t18,
R.drawable.t19,R.drawable.t20};
ImageButton b1,b2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_table);
b1 =(ImageButton) findViewById(R.id.buttonback);
b2=(ImageButton) findViewById(R.id.buttonnext);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
//imageView.setImageResource(imageAdapter.mThumbIds[position]);
imageView.setImageResource(img[position]);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
imageView.setImageResource(img[position]-1);
img[position]--;
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
imageView.setImageResource(img[position]+1);
img[position]++;
}
});
}
}
On your code you're not incrementing and decrementing your position variable at all. And your logic seems somewhat wrong. That's why you're getting some random IDs.
If you already have your img array with the Drawables IDs you want, you can simply set your position variable to zero and remove the final from it, and then increment it and decrement it directly.
For example, change this:
img[position]--;
To this:
img[--position];
And set:
int position = 0; // Default value.
Later, change the method ImageView#setImageResource to ImageView#setImageDrawable. Like:
Drawable myDrawable = getResources().getDrawable(img[position]); // Get the Drawable Object.
imageview.setImageDrawable(myDrawable); // Set the Drawable on your ImageView.
Also, consider using a List like ArrayList instead of a simple array.
EDIT: As you asked on the comments, you can start over again by reseting your position variable to zero if you're on the last image. You can do that by getting the length of the array. Something like:
if (position >= img.length) {
position = 0;
}
create a variable position at class scope and not inside onCreate() method. then in your b1 onClick() method decrement position and then show image, posting some code to demonstrate the same: ->
// at class level and not inside `onCreate()`
ImageButton b1,b2;
int position = 0; // Initializing with default value
// then inside onCreate()
position = i.getExtras().getInt("id");
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
position--;
if(position < 0){
position = img.length;
}
imageView.setImageResource(img[position]);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
position++;
if(position > img.length - 1){
position = 0;
}
imageView.setImageResource(img[position]);
}
});
Inside onClick() for b1:
imageView.setImageResource(img[position]-1);: this line of code is getting the id of drawables from img array and decreasing that value by 1.
But what you want is to display previous image so you need to modify your code to:
imageView.setImageResource(img[**position-1**]);
similary modify your code for b2 onCLick
imageView.setImageResource(img[**position+1**]);
I have next and previous button for changing the image. When activity launch, image comes from previous activity. I use bundle object for getting image on my current activity. Actually 2 images use for pass it on bundle(image_a_inner and image_a_outer). One image overlap on second image and set on custom view. Now i want to when any image comes from bundle then i press next button or previous button then according to position image will be change. For example, images like A_Z alphabet. When i press on D image then it display on my activity using bundle and when i press next button then E image will be shown or when i press previous button then C image will be shown. Below is my code.
private DrawingView mDrawingView;
Bundle extras = getIntent().getExtras();
int imageRes1 = extras.getInt("picture1");
int imageRes2 = extras.getInt("picture2");
mDrawingView = (DrawingView) findViewById(R.id.drawing_view);
mDrawingView.setShape(imageRes1, imageRes2);
btn_next = (Button) findViewById(R.id.btn_next);
// btn_next.setOnClickListener(this);
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
initializeMP();
playsound.start();
if(imageRes1==R.drawable.img_a_inner||imageRes2==R.drawable.img_a){
mDrawingView.setShape(R.drawable.img_b_inner, R.drawable.img_b);
index++;
}
else if(imageRes1==R.drawable.img_b_inner||imageRes2==R.drawable.img_b){
mDrawingView.setShape(R.drawable.img_c_inner, R.drawable.img_c);
index++;
}
else if(imageRes1==R.drawable.img_c_inner||imageRes2==R.drawable.img_c){
mDrawingView.setShape(R.drawable.img_d_inner, R.drawable.img_d);
index++;
}
else if(imageRes1==R.drawable.img_d_inner||imageRes2==R.drawable.img_d){
mDrawingView.setShape(R.drawable.img_e_inner, R.drawable.img_e);
index++;
}
}
});
btn_prev = (Button) findViewById(R.id.btn_prev);
// btn_prev.setOnClickListener(this);
btn_prev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
initializeMP();
playsound.start();
if(imageRes1==R.drawable.img_b_inner||imageRes2==R.drawable.img_b){
mDrawingView.setShape(R.drawable.img_a_inner, R.drawable.img_a);
index--;
}
else if(imageRes1==R.drawable.img_c_inner||imageRes2==R.drawable.img_c){
mDrawingView.setShape(R.drawable.img_b_inner, R.drawable.img_b);
index--;
}
else if(imageRes1==R.drawable.img_d_inner||imageRes2==R.drawable.img_d){
mDrawingView.setShape(R.drawable.img_c_inner, R.drawable.img_c);
index--;
}
});
}
If you have lists for all images in advance, declare them as arrays.
Otherwise, you can pass them using bundle with getIntArray() and putIntArray().
Now, you have lists of images like this,
// These are can be declared as member or static variables.
int[] innerPictures = {R.drawable.image_a_inner, R.drawable.image_b_inner, ...}
int[] pictures = {R.drawable.image_a, R.drawable.image_b, ...}
or
int[] innerPictures = extras.getIntArray("innerPictures");
int[] pictures = extras.getIntArray("pictures");
And you need the index of image to be displayed at the first time, it can be also passed as a extra
int displayingIndex = extra.getInt("pictureIndex"); // it has to be member variable to use inside of listener
So code is like below,
private DrawingView mDrawingView;
Bundle extras = getIntent().getExtras();
int[] innerPictures = ...
int[] pictures = ...
displayingIndex = extra.getInt("pictureIndex");
mDrawingView = (DrawingView) findViewById(R.id.drawing_view);
mDrawingView.setShape(innerPictures[displayingIndex], pictures[displayingIndex]);
btn_next = (Button) findViewById(R.id.btn_next);
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initializeMP();
playsound.start();
if (displayingIndex + 1 == innerPictures.length) return;
displayingIndex++;
mDrawingView.setShape(innerPictures[displayingIndex], pictures[displayingIndex]);
}
});
btn_prev = (Button) findViewById(R.id.btn_prev);
btn_prev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initializeMP();
playsound.start();
if (displayingIndex == 0) return;
displayingIndex--;
mDrawingView.setShape(innerPictures[displayingIndex], pictures[displayingIndex]);
});
}
Sorry for bad indentation.
In my projects I kept different images for categories. When I click on each category image I am passing its category id to other page statically and setting the drawable image of that category in the new page.
My Code:
Firstpage.java
public static String categoryid;
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="0";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="1";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="2";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
Nextpage.java
public static String catid = Firstpage.categoryid;
ImageView categorytype=(ImageView)findViewById(R.id.imageView1);
if(catid=="0")
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid=="1")
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid=="2")
{
categorytype.setBackgroundResource(R.drawable.image3);
}
First time when I am clicking on the category image it is passing the category id to the next page and that particular image is setting in the nextpage. After that I clicked the back button(android back button) and went to Firstpage.java and again clicked on other image. But this time also the same image stored. The category id didnt changed. The category id is not refreshing...How to refresh the category id? Any suggestion will be thankful.....
You are comparing two strings by == operator, instead you should compare by equals method, try following:
if(catid.equals("0"))
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid.equals("1"))
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid.equals(2"))
{
categorytype.setBackgroundResource(R.drawable.image3);
}
Don't use static variables for this. Pass the category ID to your Nextpage activity through the intent. In Firstpage.java:
public static final String CATEGORY_KEY = "category";
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(this,Nextpage.class);
myIntent.putExtra(CATEGORY_KEY, "0");
startActivityForResult(myIntent, 0);
}
});
Then retrieve it in the onCreate(Bundle) method of Nextpage.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String categoryid = intent.getStringExtra(Firstpage.CATEGORY_KEY);
. . .
}
The reason your method doesn't work is that Nextpage.catid is initialized when the class is loaded, but the assignment statement is not executed again unless the class is unloaded and needs to be reloaded.
I think problem is here you are comparing String values using this if(catid=="0") Which you should be compare it using if(catid.trim().equals("0"))
Update this change in your code and check it.
I'm trying to put the contents of List mCartList; into a the sms_body below, eg: Cheeseburger, Hamburger, Fries (so it can be sent through sms). I can pass a string so I know it works. I'm not a programmer at all and it's been a month of me doing trial & error.
Below the activity calls the contents of mCartList into a List so they can be removed. Tell me whatever else you need to help me solve this. Thank you in advance.
private ProductAdapter mProductAdapter;
// This List into the order button below
private List<Product> mCartList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCart();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
}
});
Button orderButton = (Button) findViewById(R.id.orderButton);
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
// The above List<Product> mCartList ia displayed in the window of the app
intent.putExtra("sms_body", "mCartList"); // I want the results of List<Product> mCartList to go here - I can not just insert the variable I just get errors and can't compile
startActivity(intent);
}
});
Button removeButton = (Button) findViewById(R.id.ButtonRemoveFromCart);
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
}
}
mProductAdapter.notifyDataSetChanged();
}
});
}
Here is how this works. It's a 4 tab list with different items in each tab, 3 of which or products. Customer clicks on the item and they see a description, click add to cart, then your back at the menu. The 4th tab is a the order of what was just selected that is to populate the sms body. I have been able to pass a variable with the text "Hello World". I'm figuring the result of List mCartList can populate the sms body. I'm assuming the List can not just be inserted into the body of a forn without being converter. Let me know if you need anymore info. I'm not a programmer, I have seen similar but nothing that doesn't work without writing other files I got from a tutorial. Thank you in advance.
If all the products are added to your mCartList, it's just a matter of concatenating the String output of the Products together as follows:
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
StringBuilder builder = new StringBuilder();
for(Product p : mCartList){
builder.append(p.toString());
builder.append('\n');
}
intent.putExtra("sms_body", builder.toString());
startActivity(intent);
}
});
make sure your Product has a toString() method defined as follows (example Product guess):
public class Product{
String productName;
public String toString(){
return productName;
}
}
It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.