Passing image Id to custom listview adapter - android

How can I pass an Image resource Id to my custom adapter? I have a check box in an activity called routedetails . When the checkbox is checked I want to display a check mark next to that item in the listview. But to do this I need to pass the imageId to the custom adapter. I tried doing it with an intent putExtra. But that does not work.
Heres my RouteDetails.java with the checkbox code
public class RouteDetails extends AppCompatActivity {
ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);
//back button for route details view
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
///////checkbox///////////////////////////////////////////
routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
////// final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
//checkImageView.setImageResource(R.drawable.checkmark);
Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
startActivity(check);
/////////////////////////////////////////////
//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);
//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));
//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
routeImage.setImageResource(mImageResource);
And here's the custom adapter
class CustomAdapter extends ArrayAdapter<CharSequence>{
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0));
////////////////////////////////////////
return customView;
}
And here's the adapter being used in my main activity
list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
Any help would be appreciated

Basically you create two activities. Let say, MyListViewActivity containing a ListView whose items are nothing but custom views which hold an ImageView and a TextView;
then a CheckBoxActivity holding the CheckBox elements.
When a list item is clicked in MyListViewActivity, you start the CheckboxAtivity using startActivityForResult() method.
Finaly, in the CheckBoxActivity when a checkBox item is checked its textValue is send back to MyListViewActivity for updating the corresponding imageView.
See below code snippets:
Layout file for MyListViewActivity : activity_my_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_my_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="YourPackageNameHere.MyListViewActivity" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Layout file for custom list item: list_single.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/img"
android:layout_width="40dp"
android:layout_height="40dp"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_gravity="center_horizontal|center_vertical" />
</LinearLayout>
</TableRow>
</TableLayout>
Layout file for CheckBoxActivity: activity_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_checkbox"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="YourPackageNameHere.CheckboxActivity">
<CheckBox
android:text="CheckBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox1" />
<CheckBox
android:text="CheckBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox2" />
</LinearLayout>
code for MyListViewActivity :
package YourPackageNameHere;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyListViewActivity extends AppCompatActivity {
ImageView img;
ListView list;
private static final int MY_REQUEST_CODE= 1;
String[] itemNames = {
"Google Plus",
"Twitter",
"Windows",
"Bing",
"Itunes",
"Wordpress",
"Drupal"
} ;
Integer[] imageId = {
R.drawable.ic_home_black_18dp,
R.drawable.ic_account_circle_black_18dp,
R.drawable.ic_fingerprint_black_18dp,
R.drawable.ic_help_black_18dp,
R.drawable.ic_settings_black_18dp,
R.drawable.ic_power_settings_new_black_18dp,
R.drawable.ic_directions_run_black_18dp
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list_view);
CustomList adapter = new CustomList(MyListViewActivity.this, itemNames, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyListViewActivity.this, "You Clicked at " + itemNames[+ position], Toast.LENGTH_SHORT).show();
//get the image that has been clicked
img= (ImageView) view.findViewById(R.id.img);
//Starting the CheckBoxAtivity for result
Intent mIntent = new Intent(getBaseContext(), CheckboxActivity.class);
startActivityForResult(mIntent, MY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
switch (result){
case "CheckBox1":
img.setImageResource(R.drawable.ic_gps_fixed_black_18dp);
break;
case "CheckBox2":
img.setImageResource(R.drawable.cast_ic_notification_0);
break;
}
}
}
}//onActivityResult
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemNames;
private final Integer[] imageId;
public CustomList(Activity context, String[] itemNames, Integer[] imageId) {
super(context, R.layout.list_single, itemNames);
this.context = context;
this.itemNames = itemNames;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(itemNames[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
}
code for ChecboxActivity:
package YourPackageNameHere
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class CheckboxActivity extends AppCompatActivity {
CheckBox mCheckBox1;
CheckBox mCheckBox2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkbox);
mCheckBox1 = (CheckBox) findViewById(R.id.checkBox1);
mCheckBox2 = (CheckBox) findViewById(R.id.checkBox2);
mCheckBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(mCheckBox1.isChecked()){
sendResultToLisViewActivity((String) mCheckBox1.getText()); //send the text string of mCheckBox1 to MyListViewActivity
}
}
});
mCheckBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(mCheckBox2.isChecked()){
sendResultToLisViewActivity((String) mCheckBox2.getText()); //send the text string of mCheckBox1 to MyListViewActivity
}
}
});
}
public void sendResultToLisViewActivity(String mStringExtra){
Intent returnIntent = new Intent();
returnIntent.putExtra("result",mStringExtra);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}
Lastly in your MainActivity onCreate() method you start MyListViewActivity as follows:
Intent i = new Intent(MainActivity.this, MyListViewActivity.class);
startActivity(i);
Ps: I referred to this link for creating the Custom ListView with Images and Text.

Related

I am new in android,i want to delete a row on clicking delete button that are shown in front of each row in list view

This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}

Android How can I pass string values from database to TextView in another activity in Android?

I want to display values from my COLUMN_INGRIDIENTS column from my db to a TextView in another activity when a certain data on list in my Main activity is clicked.
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/myListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/recipeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
Main.java
package com.example.viewer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends Activity {
public final static String TAG_INGRIDIENTS="com.example.getlistfromdb.INGRIDIENTS";
private recipelistHelper dbrecipelistHelper = null;
private Cursor ourCursor = null;
private recipeAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView) findViewById(R.id.myListView);
dbrecipelistHelper = new recipelistHelper(this);
dbrecipelistHelper.createDatabase();
dbrecipelistHelper.openDatabase();
ourCursor=dbrecipelistHelper.getCursor();
startManagingCursor(ourCursor);
adapter = new recipeAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent i=new Intent(Main.this, Activity2.class);
String ingridients = null;
i.putExtra(TAG_INGRIDIENTS,ingridients);
startActivity(i);
}
};
class recipeAdapter extends CursorAdapter {
recipeAdapter(Cursor c){
super(Main.this, c);
}
#Override
public void bindView (View row, Context ctxt, Cursor c)
{
recipeHolder holder = (recipeHolder)row.getTag();
holder.populateFrom(c, dbrecipelistHelper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row=inflater.inflate(R.layout.list, parent, false);
recipeHolder holder = new recipeHolder(row);
row.setTag(holder);
return(row);
}
}
static class recipeHolder {
private TextView name=null;
recipeHolder(View row){
name=(TextView)row.findViewById(R.id.recipeText);
}
void populateFrom(Cursor c, recipelistHelper r){
name.setText(r.getName(c));
}
}
}
Activity2.java
package com.example.viewer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Activity2 extends Activity {
String ingridients = null;
String procedure = null;
private TextView txtIngridients = null;
private TextView txtProcedure = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
ingridients=this.getIntent().getStringExtra(Main.TAG_INGRIDIENTS);
//procedure=this.getIntent().getStringExtra(Main.TAG_PROCEDURE);
txtIngridients=(TextView)findViewById(R.id.ingridientText);
//txtProcedure=(TextView)findViewById(R.id.procedureText);
txtIngridients.setText(ingridients);
//txtProcedure.setText(procedure);
}
}
view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ingridientText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:text="A" />
</RelativeLayout>
Use adapter.getItem to get cursor of selected row in ListView :
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor selectedCursor=(Cursor)adapter.getItem(position);
// get ingridients coulmn value from selectedCursor
selectedCursor.moveToPosition(position);
String ingridients = dbrecipelistHelper.getName(selectedCursor);
// your code here
}
In your onItemClickListener you assign null to your string:
String ingridients = null;
and pass this String to your next Activity. This will be null. You have to fetch your data before you initialize your ingridients variable and set it to the desired String.

Inflating a layout on listitem click to get the custom view from array

Ok, I am facing a problem while inflating a layout for listitem click. I am very new to android so please consider me in learning Phase. I have successfully implemented the customize
listview after 1 day of effort. As I told, I am newbie.
But now I want to make a listitem clickable, like when I click on list item it inflate a layout which have a imageview and a textview.
On each click these two imageview and textview will take the value from array according to position click.
I can do this by using the intent like this :
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
if (position == 0) {
Intent int0 = new Intent(getApplicationContext(), Activity.class);
startActivity(int0);
}
But let supposed the situation where I have 1000 items in array,and i need to make each item
clickable. So in this case their will need of 1000 new class's and layout for intent that i don't wants.
I don't know, that how could I explain it. But i will try:
Please see picture for more clearance :
I have implemented the customize listview.
Now what I want to do :
When a user click on item then get a view like this: means top screen will show the image and bottom screen will show the text, that are coming from array's.
Here is my complete code for reference : MainActivity.java
package com.diljeet.customlistview;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
ListView list;
String[] web = { "Diljeet", "sweet", "kaur", "preet", "manjeet", "dillun",
"rupal" };
Integer[] imageId = { R.drawable.image1, R.drawable.image2,
R.drawable.image3, R.drawable.image4, R.drawable.image5,
R.drawable.image6, R.drawable.image7
};
String textonclick[] = { "a", "b", "c", "d", "e", "f", "i", "j", "k" };
Integer[] imageonclick = { R.drawable.r, R.drawable.ra, R.drawable.rb,
R.drawable.rc, R.drawable.rd, R.drawable.re, R.drawable.rf
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomList adapter = new CustomList(MainActivity.this, web, imageId);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key",web[position]);
intent.putExtra("key1",imageonclick[position]);
intent.putExtra("key2",textonclick[position]);
startActivity(intent);
}
});
}
}
CustomList.java
package com.diljeet.customlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String>{
Activity context;
String[] web;
Integer[] imageId;
CustomList(Activity context,
String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
SecondActivity.java
package com.diljeet.customlistview;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class SecondActivity extends Activity {
public void oncreate(Bundle savedInstanseState) {
super.onCreate(savedInstanseState);
setContentView(R.layout.getintant);
TextView txtnew = (TextView) findViewById(R.id.get_txt);
ImageView imgnew = (ImageView) findViewById(R.id.get_img);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("key");
String email = i.getStringExtra("key2");
txtnew.setText(name);
Bitmap image = imgnew.getDrawingCache();
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("key1");
image.setImageBitmap(bmp);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
list_single.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_marginLeft="50dp"
android:layout_height="wrap_content" />
</RelativeLayout>
getintant.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/get_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/get_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:textSize="20sp" />
</RelativeLayout>
One thing i want to say that onclick we are getting the value from array's, textonclick,imageonclick from MainActivity.
Many many thanks in advance, and please pardon me for complex explanation.
Use the below. You can pass values between activities using intent.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key",web[position]);
intent.putExtra("key1",imageonclick[position]);
intent.putExtra("key2",imageId[position]);
startActivity(intent);
}
});
Edit:
For image
int id = i.getIntExtra("key2",R.drawable.ic_launcher);
imgnew.setImageResource(id);
http://developer.android.com/reference/android/content/Intent.html#getIntExtra(java.lang.String, int)
public int getIntExtra (String name, int defaultValue)
Added in API level 1
Retrieve extended data from the intent.
Parameters
name The name of the desired item.
defaultValue the value to be returned if no value of the desired type is stored with the given name.
Returns
the value of an item that previously added with putExtra() or the default value if none was found.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
Intent int0 = new Intent(getApplicationContext(), Activity.class);
int0.putExtra("text",textonclick[position]);
startActivity(int0);
}
use this to pass your list item values from one activity to another .

display selected image on another page from image slider

Can someone help me with the code-I am having image slider containing multiple images and if I select any particular image and click on button that selected image should open on another page/activity.
I tried a lot but unable to display selected image on another page/activity.
So, please help me.
Thanks in advance.
**Main.java**
package com.example.imagesliderdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
#SuppressWarnings("deprecation")
public class Main extends Activity {
private Gallery topsgallery;
private ImageView imgView;
int GalItemBg;
private Integer[] Imgid = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
imgView = (ImageView)findViewById(R.id.ImageViewTops);
imgView.setImageResource(Imgid[0]);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
private int position;
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent nextScreen = new Intent(Main.this, OpenImage.class);
Intent nextScreen=new Intent(getApplicationContext(),OpenImage.class);
nextScreen.putExtra("image",R.drawable.ic_launcher);
startActivity(nextScreen);
}
});
topsgallery = (Gallery) findViewById(R.id.gallery1);
topsgallery.setAdapter(new AddImgAdp (this));
topsgallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
imgView = (ImageView)findViewById(R.id.ImageViewTops);
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.Gallery1);
GalItemBg = typArray.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
return imageView;
}
}
}
**Other activity file OpenImage.java**
package com.example.imagesliderdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class OpenImage extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
ImageView image = (ImageView) findViewById(R.id.imageview);
int image_link = getIntent().getIntExtra("image_url", R.drawable.ic_launcher);
image.setImageResource(image_link);
Button btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});
}
}
**activity_main.xml**
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:overScrollMode="always"
android:isScrollContainer="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideInset"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical">
<LinearLayout
android:id="#+id/LinearLayoutTops"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="vertical">
<TextView
android:gravity="center"
android:text="#string/tops"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/LinearLayoutTopsGallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spacing="10dp" />
<ImageView
android:id="#+id/ImageViewTops"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/imageslide"/>
</LinearLayout>
</LinearLayout>
<Button android:id="#+id/btnNextScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send to Next Screen"
android:layout_marginTop="15dip"/>
</LinearLayout>
</ScrollView>
**Another Activity screen2.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnClose"
android:layout_width="151dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dip"
android:text="Close" />
<ImageView
android:id="#+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
You can use fragment,
http://developer.android.com/guide/components/fragments.html
this page have a example, maybe can help you.
Create a global variable to get the position of Slider(Let suppose that variable be pos).Now in getView of your slider adapter code like this
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
pos=position;
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
return imageView;
}
Now on button click code like this:
btnNextScreen.setOnClickListener(new View.OnClickListener() {
private int position;
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent nextScreen = new Intent(Main.this, OpenImage.class);
Intent nextScreen=new Intent(getApplicationContext(),OpenImage.class);
//Sending data to another Activity
nextScreen.putExtra("id",Imgid[pos]);
Log.e("n", Imgid[pos]);
startActivity(nextScreen);
}
});
Just pass the selected image id value in the Gallery on click listener.
topsgallery.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
{
// TODO Auto-generated method stub
Intent fullImage = new Intent(YourActivity.this,FullImageView.class)
fullImage.putExtra("image_url",R.drawable.image);
startActivity(fullImage);
}
});
consider the following steps :
#1 Create a new activity say for ex : FullImageView with the following view and declare that in manifest.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/android" />
</ImageView>
</LinearLayout>
3 : Receive the intent in onCreate of FullImageView activity
ImageView image = (ImageView) findViewById(R.id.image);
int image_link = getIntent().getIntExtra("image_url", R.drawable.default);
4 : Set the URL to your ImageView.
imageView.setImageResource(image_link);
Please feel free if you face any issues regarding this.
You can put the intent inside the adapter... and then do something like this (Note that you need to pass the context to the adapter):
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen=new Intent(context,OpenImage.class);
nextScreen.putExtra("image",ImgId[pos]);
startActivity(nextScreen);
}
});
return imageView;
}

GridView and ImageButton Weird issue

Hi all I have custom grid view with imageButton and textView as follows
Here i have used imageButton.. The problem is the grid is not clickable.. But if i use here imageView it works fine but UI is not appropriate.
Here is my layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp"
>
<ImageButton
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/newlocation"
android:background="#drawable/btnbackground"
/>
<TextView
android:id="#+id/SpeakerName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15sp"
android:text="Some Speaker"
/>
Here is my adapter
package com.tt.cc;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SavedConferencesGridAdapter extends ArrayAdapter<String>{
Context mContext;
List<String> confernceList;
public SavedConferencesGridAdapter(Context context, int textViewResourceId, List<String> confernceList)
{
super(context,textViewResourceId,confernceList);
this.confernceList = confernceList;
this.mContext = context;
Log.e("TAG", confernceList.size()+"");
}
int[] picIds = new int[] { R.drawable.newschedule,R.drawable.newexhibitors,
R.drawable.newsponsers, R.drawable.newlocation,
R.drawable.newfavourites, R.drawable.newreminder,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info };
#Override
public int getCount() {
// TODO Auto-generated method stub
return confernceList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.entity, null);
TextView tv = (TextView)v.findViewById(R.id.SpeakerName);
tv.setText("tt");
/*ImageView iv = (ImageView) v.findViewById(R.id.profilePic);
iv.setImageResource(picIds[position]);*/
}
else
{
v = convertView;
}
return v;
}
}
and here is my activity
public class SavedConferencesActivity extends Activity{
GridView confereneceGridView;
ArrayAdapter<String> conferneceAdapter;
Button btnUpdate;
List<String> conferenceList;
TextView txtHeading;
Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.homegridlayout);
initialize();
confereneceGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SavedConferencesActivity.this, conferenceList.get(position)+"", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
conferneceAdapter = new SavedConferencesGridAdapter(this, android.R.layout.simple_list_item_1, conferenceList);
confereneceGridView.setAdapter(conferneceAdapter);
}
private void initialize() {
confereneceGridView = (GridView) findViewById(R.id.gridOfConference);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
txtHeading = (TextView) findViewById(R.id.txtTag);
conferenceList = new ArrayList<String>();
conferenceList.add("AA");
conferenceList.add("BB");
conferenceList.add("CC");
if (conferenceList.size() == 0)
txtHeading.setText("No conferences saved");
else
txtHeading.setText("Selected Conferences");
}
}
Please help me in solving this problem. Or if any alternative available..
Simple. Provide this attribute for the ImageButton ,
android:focusable="false"
This problem usually occurs when there is a focussable element in the Grid.(Eg:Buttons, ImageButton etc).
Reason of this ImageButton is by Default is clickable and focusable, so Focus and click event never goes to ItemView.
Set Properties
android:focusable-"false"
and
android:clickable="false"
Your item's Layout should be:
<LinearLayout ...
android:descendantFocusability="blocksDescendants">
<ImageButton ...
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
Don't forget setOnClickListener for ImageButton in Adapter.
in your adapter class,
before you return the view "v", add the "onClickListener" to "v"
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position, Toast.LENGTH_SHORT).show();
}
});

Categories

Resources