Android ListView - onItemClickListener - java

I'm beginning in mobile application development and I want to know how to send an item from a ListView to appear in another activity; Then I can show more information about each item.
I managed to display the title and description with the following code:
MainActivity
TextView txt = (TextView)findViewById(R.id.textView1);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("title", txt.getText());
startActivity(intent);
SecondActivity
TextView txt = (TextView)findViewById(R.id.show_textView1);
Bundle b = this.getIntent().getExtras();
String val = b.getString("name");
txt.setText(val);
but how do I set putExtra for an image to display in the next Activity ?
P.S. everything is working fine, the xml file where the item details will be shown is set.

What is the source of the image?
If a file, pass in the String to the file location.
bundle.putString("file-loc",fileLocation);
If a resource, pass in the resource.
bundle.putInt("resource-id",resid);
If it's just a bitmap, you can actually pass it directly, as a Parcelable.
bundle.putParcelable("bitmap",bitmap);

You can send the ImageView's id (R.drawable.your_image) and then fetch it and show it in the ImageView of other activity

Related

Cant set text to EditText in DialogFragment

I have a button in listview row that when I click on it I want a dialogFragment to be open and set the text of an edit text (that located inside the dialogFragment) to some String.
The problem is: the app shut down when it comes to the line of the settext method.
This is the code I use to open the dialogFragment and set text to it.
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
TrempData data = adapter.getItem(position); //from here im getting the data that i want to set to the edit text.
Addtremp trempDialog = new Addtremp();
trempDialog.show(manager, "Addtremp");
trempDialog.from.setText(data.get_from());
trempDialog.to.setText(data.get_to());
trempDialog.date.setText(data.get_date());
trempDialog.time.setText(data.get_time());
trempDialog.extra.setText(data.get_extras());
}
Hope someone could help me.
Thanks.
Your App will surely crash due to NullPointerException. Because you are trying to set data on UI which is not rendered yet.
What steps should follow?
Pass data to DialogFragment which is going to display on UI in a form of arguments.
Create callback which will inform you when UI is rendered on Dialog. Check this Callback to a Fragment from a DialogFragment
. On getting listener you could set data on your UI components.
Personally I prefer solution1 and for that you should read passing argument to DialogFragment

Save dynamicaly added items in layout

How do I save dynamicaly (through code) added items in layout? I mean, I added two imageViews into layout through code, but when I switch to another layout, and then get back to this one, imageViews are gone (they aren't here).
Code:
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
layout.addView(imageView);
When you say a second layout, do you mean a second activity ?
If yes, you can use the intent to transmit the images to the second layout, and then transmit it back to the first activity.
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
bitmaps.add(yourimage);
Intent intent = new Intent(A1.this, A2.class);
intent.putParcelableArrayListExtra("bitmaps", bitmaps);
startActivity(intent);
You can take it in the second Activity with :
Intent intent = getIntent();
if(intent.hasExtra("bitmaps")){
ArrayList<Bitmap> bitmaps= intent.getExtras().getParcelableArrayList("bitmaps");
}

send arraylist from one to another activity into listview android [duplicate]

This question already has an answer here:
Passing arraylist in intent from one activity to another
(1 answer)
Closed 7 years ago.
I am making an android app. It is simple and based on quotes. I have a database of around 300 quotes divided in 5 categories (movies, books, etc.) and I show them at random when a user clicks on a category, in a TextView. Now I want the users to have an option to save their favorite quotes, so I have another activity called Favorites where I want the favorites to show in a ListView.
For this I think that the best way is to have all the favorites the user will put in a String ArrayList, and then send the whole ArrayList to the Favorites activity where it will put the strings from the ArrayList in the ListView. But, every time I try to send an ArrayList to the other activity, my app crashes.
I only managed to send the current string that is shown on screen like this
text.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
intent.putExtra("key", text.getText());
Context context = getApplicationContext();
CharSequence text = "Added to favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
And then I take it and put it in the other activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
final ListView lista = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
tekst = intent.getStringExtra("key");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lista.setAdapter(adapter);
listItems.add(tekst);
adapter.notifyDataSetChanged();
}
But then if I try to add another favorite, it just overwrites the previous one. So how should I deal with this? How to send all the favorites that the user wants to put? Is ArrayList the best option or is there another way?
Activity A :
ArrayList<String> list = new ArrayList<String>();
intent.putExtra("yourlist", list);
startActivity(intent);
Activity B:
ArrayList<String> list = getIntent().getSerializableExtra("yourlist");
I hope its help you..!
Your previous ArrayList is overwritten because every time you navigate to the Favorites activity, it gets recreated and so does the ArrayList. The data is not persisted. The best option would be to use a database and save the item to the database from one activity. Then the favorite items can be retrieved from the database inside the Favorites activity.

Click listview item and display image

im trying to create a listview where if you press an item on that list, it displays an image in fullscreen. I have about 10 different items in the list and I want to display different images for each item.
I used this tutorial: http://www.androidhive.info/2011/10/android-listview-tutorial/
But instead of showing the name of my string item, i want it to show an image. How do i fix this?
I have been trying to check other questions, but they have been kinda hard to follow since im new to this.
First of all you need to have images in your drawable folder for all different items(in list view)
Change the single_list_item.xml to
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
change your SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
ImageView productimage = (ImageView) findViewById(R.id.image);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
switch(product){
case "item1":
productimage.setImageDrawable(R.drawable.image1);
break;
case "item2":
productimage.setImageDrawable(R.drawable.image2);
break;
case "item3":
productimage.setImageDrawable(R.drawable.image3);
break;
.
.
.
.
.
//upto all 10 images
}
}
}
You should be able to do this with only a few changes to the tutorial code.
First, in single_list_item_view.xml, you'll need to use an ImageView instead of a TextView, since you want to show an image. You can find documentation for image views, including what attributes they support, on the Android developer site.
Second, you'll need to change the line that looks up the TextView to find your new ImageView instead. This will only require changing the following line:
TextView txtProduct = (TextView) findViewById(R.id.product_label);
to:
// Assuming you gave your ImageView the id "product_image" in single_list_item_view.xml
ImageView productImage = (ImageView) findViewById(R.id.product_image);
You'll need to add the images that you want to show into your project. The simplest place for these to go is in the res/drawable folder. The name of the image files will determine their "ids". For example, if you have res/drawable/photoshop.png, you can refer to it with the id R.drawable.photoshop.
Next you need to figure out which image to show in SingleListItem. The key part of how clicking on an item in the list shows something else is in SingleListItem:
Intent i = getIntent();
String product = i.getStringExtra("product");
Correspondingly, in AndroidListViewActivity:
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
i.putExtra("product", product);
startActivity(i);
The Intent is how you send information from the list activity to the activity that shows the item. In this case, the information being sent is which item to show. You have a few options about how to do this part. One simple way is just to inspect the product string and choose the appropriate drawable:
int imageId = -1;
if (product.equals("Adobe After Effects")) {
imageId = R.drawable.after_effects;
} else if (product.equals("Adobe Bridge")) {
imageId = R.drawable.bridge;
} else if ...
... // All your other cases
}
This approach obviously doesn't scale very well, but it will work okay for your simple example. Another possible approach would be to pass the image id in the Intent, rather than the product name, for example:
// In AndroidListViewActivity:
i.putExtra("product", R.drawable.after_effects);
// In SingleListItem:
int imageId = i.getIntExtra("product", -1);
// -1 in the call above is the value to return if "product" is not in the Intent
The final thing you need to do is set the Drawable for the ImageView you found earlier:
// Make sure to check that the id is valid before using it
if (imageId != -1) {
Drawable d = getResources().getDrawable(imageId);
productImage.setDrawable(d);
}
getResources() fetches the Resources object for you application. You can use the Resources object to look up things like strings and drawables you've defined in your res folder. The tutorial you're following also uses it to look up an array of strings in the res folder. Again, you can see everything Resources supports on the Android developer site.
Instead of showing the item/text in SingleListItem class you could use the passed item to check which image should be displayed in an imageview. Something like that:
public class SingleListItem extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
// TextView txtProduct = (TextView) findViewById(R.id.product_label);
ImageView image = (ImageView) findViewById(R.id.someImage);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
if (product.equals("item1")) {
image.setDrawableResource(R.drawable.YOURIMAGE);
} else if (product.equals("item2"))
image.setDrawableResource(R.drawable.ANOTHERIMAGE);
}
}

Can't update TextView from another activity

I have an activity with a TextView that needs to be updated from a second activity.
I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView
within the 2nd activity it crashes. My code:
1st Activity (where the TextView is defined in my xml):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
Then in my 2nd activity:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
but it crashes when I try to pull in as a TextView:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
Please help.
You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).
You trying to cast String to TextView. The code that crashes is equivalent of:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
You should do instead:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
This line here:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
is attaching a String along with the intent, not a TextView.
You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.
Something that solved part of this problem for me was setting the receiving String variables to null like this:
public String param1new = null;
public String param2new= null;
My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.

Categories

Resources