I'm trying to create a kind of game using Android Studio. Till now I have done a gridview wich shows players stored in a database. I have had some problems with gridView.setOnItemClickListener, I have had to do it by putting the code into gridView's Adparter.class so if you know how I can do that into gridView's activity please tell me.
My problem now is that when you click on a player a popup window appears in which you could change the player's name or his genre. When you click on Confirm's button the database will automatically been updated, but it doesn't works. I have try to do it step by step by using Toast in order to know if it run that part or not, the problem could be the context, but maybe I'm crazy.
I left you some pics and the code related to it.
Gridview's pic -> http://i.stack.imgur.com/GO4ms.png
PopUp windos's pic -> http://i.stack.imgur.com/aAvcm.png
gridView's adapter class
package es.fingerlabs.gamecohol;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdaptadorAmigos extends BaseAdapter {
private Context context;
private ArrayList<Amigo> misAmigos = new ArrayList<Amigo>();
public AdaptadorAmigos(ArrayList<Amigo> list, Context context) {
this.misAmigos = list;
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if (gridView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.item_amigo, null);
}
TextView TextoNombreJugador = (TextView)gridView.findViewById(R.id.tvNombreAmigo);
TextoNombreJugador.setText(misAmigos.get(position).getNombre());
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)gridView.findViewById(R.id.btEliminarAmigo);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(context, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
db.delete("Amigos", "id_amigo="+misAmigos.get(position).getId(), null);
misAmigos.remove(position); //or some other task
//Eliminar de la base de datos **************
notifyDataSetChanged();
}
});
// ******* THIS IS WHAT I REFER TO PUT IT ON GRIDVIEW'S ACTIVITY *******
gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,"Id "+misAmigos.get(position).getId()+" Vidas "+misAmigos.get(position).getVidas(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
context.startActivity(intent);
}
});
return gridView;
}
#Override
public int getCount() {
return misAmigos.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
gridView's class
package es.fingerlabs.gamecohol;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class SeleccionarAmigos extends AppCompatActivity {
private ArrayList<Amigo> misAmigos;
private GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amigos);
gridView = (GridView) findViewById(R.id.gvAmigos);
refrescarLista();
/* IF I PUT THAT HERE IT DOES NOTHING
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
Toast.makeText(getApplicationContext(),misAmigos.get(position).getNombre(), Toast.LENGTH_SHORT).show();
}
});*/
/*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(SeleccionarAmigos.this, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
startActivity(intent);
}
});*/
}
public void obtenerAmigos(){
misAmigos = new ArrayList<Amigo>();
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getReadableDatabase();
Cursor c = db.rawQuery(" SELECT Id_amigo,Nombre,Genero FROM Amigos ", null);
//Nos aseguramos de que existe al menos un registro
if (c.moveToFirst()) {
//Recorremos el cursor hasta que no haya más registros
do {
int id = c.getInt(0);
String nombre= c.getString(1);
String genero= c.getString(2);
Amigo nuevoAmigo = new Amigo(nombre,genero,null);
nuevoAmigo.setId(id);
this.misAmigos.add(nuevoAmigo);
} while(c.moveToNext());
}
db.close();
}
public void refrescarLista(){
obtenerAmigos();
AdaptadorAmigos adapter = new AdaptadorAmigos(misAmigos, this);
gridView.setAdapter(adapter);
}
}
PopUp window class
package es.fingerlabs.gamecohol;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;
public class VistaAmigo extends Activity {
private int id;
private String nombre;
private String genero;
private EditText etNombre;
private EditText etGenero;
private Button btConfirmar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vistaamigo);
etNombre = (EditText) findViewById(R.id.etNombreVistaAmigo);
etGenero = (EditText) findViewById(R.id.etGeneroVistaAmigo);
btConfirmar = (Button) findViewById(R.id.btConfirmarAmigo);
Intent i = getIntent();
i.getIntExtra("Id", id);
nombre = i.getStringExtra("Nombre");
genero = i.getStringExtra("Genero");
etNombre.setHint(nombre);
etGenero.setHint(genero);
btConfirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(VistaAmigo.this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put("nombre", etNombre.getText().toString());
valores.put("genero", etGenero.getText().toString());
db.update("Amigos", valores, "id_amigo="+id, null);
Toast.makeText(VistaAmigo.this.getBaseContext(),"Nombre: "+etNombre.getText().toString()+" Genero: "+etGenero.getText().toString()+
"Cambios realizados",Toast.LENGTH_LONG);
}
});
}
}
gridView's layout
<?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"
android:background="#drawable/fondogamecohol">
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/gvAmigos"
android:layout_gravity="center_horizontal"
android:numColumns="auto_fit"
android:layout_margin="10dp"
android:verticalSpacing="20dp"
android:horizontalSpacing="20dp" />
</LinearLayout>
Gridview's item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corners_white"
android:id="#+id/lyItemAmigo">
<ImageView
android:layout_width="124dp"
android:layout_height="95dp"
android:id="#+id/ivFotoAmigo"
android:background="#d8d8d8"
android:layout_marginTop="10dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:src="#drawable/ic_tag_faces_white_36dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Chrisitan"
android:id="#+id/tvNombreAmigo"
android:layout_gravity="center"
android:textColor="#333333"
android:textStyle="bold"
android:textSize="18dp"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:layout_marginLeft="14dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:gravity="right"
android:id="#+id/lyBotonesAmigo"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEditarAmigo"
android:clickable="false"
android:background="#drawable/ic_edit_black_18dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEliminarAmigo"
android:clickable="false"
android:background="#drawable/ic_delete_forever_black_18dp" />
</LinearLayout>
</LinearLayout>
PopUp window layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/PopUp1">
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_white"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Modificar amigo"
android:id="#+id/tvModificarAmigo"
android:layout_gravity="center_horizontal"
android:background="#c9ed5a"
android:gravity="center_vertical|center_horizontal"
android:textStyle="bold"
android:textColor="#ffffff" />
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre: "
android:id="#+id/tvNombreVistaAmigo"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="28dp"
android:layout_marginTop="51dp"
android:textStyle="bold"
android:textColor="#333333"
android:textSize="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNombreVistaAmigo"
android:layout_marginStart="10dp"
android:hint="Jugador 1"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/tvNombreVistaAmigo"
android:layout_toRightOf="#+id/tvNombreVistaAmigo"
android:layout_marginTop="41dp"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Genero:"
android:id="#+id/tvGeneroVistaAmigo"
android:layout_centerVertical="true"
android:layout_alignStart="#+id/tvNombreVistaAmigo"
android:textColor="#333333"
android:textStyle="bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etGeneroVistaAmigo"
android:hint="Hombre"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignStart="#+id/etNombreVistaAmigo"
android:layout_below="#+id/etNombreVistaAmigo"
android:layout_marginTop="23dp"
android:textSize="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirmar"
android:id="#+id/btConfirmarAmigo"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_green"
android:layout_marginBottom="20dp"
android:textStyle="bold"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
From what I´ve seen in your code is, that you try to get the id from an intent in your PopUp window class. You have made one thing wrong:
Intent i = getIntent();
i.getIntExtra("Id", id);
it must be:
Intent i = getIntent();
id = i.getIntExtra("Id", id); //forgott id = here
and you should give a default value to id for example id=-1 . The problem is, by updating your database, you give a non value integer and so it is not possible to update your table.
Related
I am trying to add a Menu to my activity_main.xml. I added menu.xml to the res/menu directory and inflated it to activity_main.xml.
The problem is it is not showing. Do I need something to trigger the onCreateOptionsMenu method?
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/toast"
android:title="Raise Toast"
/>
</menu>
MainActivity.java
package com.nejat.lunchlist;
import android.app.DatePickerDialog;
import android.app.TabActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TimePicker;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class MainActivity extends TabActivity {
String[] autoAddr = {"mall", "foodcourt","school","places"};
ArrayList<Restaurant> model = new ArrayList<Restaurant>();
RestaurantAdapter adapter = null;
AutoCompleteTextView addr;
ArrayAdapter<String> adapter2 = null;
ListView listView;
private AutoCompleteTextView name = null;
private AutoCompleteTextView address= null;
private RadioGroup rButton;
TabHost tabHost;
DatePickerDialog datePickerDialog;
EditText datePickerEditText;
Restaurant r = new Restaurant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.save);
datePickerEditText = (EditText) findViewById(R.id.date);
datePickerEditText.setOnClickListener(datePicker);
btn.setOnClickListener(onSave);
listView = (ListView) findViewById(R.id.restaurants);
adapter = new RestaurantAdapter(model,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(selectItem);
addr = (AutoCompleteTextView) findViewById(R.id.addr);
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,autoAddr);
addr.setThreshold(1);
addr.setAdapter(adapter2);
tabHost = (TabHost) findViewById(android.R.id.tabhost);
TabHost.TabSpec tabspec = tabHost.newTabSpec("List");
tabspec.setContent(R.id.restaurants);
tabspec.setIndicator("Restaurants");
tabHost.addTab(tabspec);
tabspec = getTabHost().newTabSpec("Details");
tabspec.setContent(R.id.details);
tabspec.setIndicator("Details");
tabHost.addTab(tabspec);
tabHost.setCurrentTab(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
private View.OnClickListener datePicker = new View.OnClickListener(){
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int mHour = cal.get(Calendar.HOUR_OF_DAY);
int mminnute = cal.get(Calendar.MINUTE);
TimePickerDialog time = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
datePickerEditText.setText(hourOfDay + "/"+ minute);
r.setDate(hourOfDay + "/"+ minute);
}
},mHour,mminnute,false);
time.show();
}
};
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
AutoCompleteTextView name = (AutoCompleteTextView) findViewById(R.id.name);
EditText note = (EditText) findViewById(R.id.note);
RadioGroup rb = (RadioGroup) findViewById(R.id.types);
r.setAddress(addr.getText().toString());
r.setName(name.getText().toString());
r.setNote(note.getText().toString());
switch (rb.getCheckedRadioButtonId()){
case R.id.sit_down:
r.setType("Sit_Down");
break;
case R.id.take_out:
r.setType("Take_Out");
break;
case R.id.delivery:
r.setType("Delivery");
break;
}
adapter.add(r);
}
};
private AdapterView.OnItemClickListener selectItem = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Restaurant r= model.get(position);
name = (AutoCompleteTextView) findViewById(R.id.name);
address = (AutoCompleteTextView) findViewById(R.id.addr);
EditText note = (EditText) findViewById(R.id.note);
rButton = (RadioGroup) findViewById(R.id.types);
tabHost.setCurrentTab(1);
note.setText(r.getNote().toString());
name.setText(r.getName().toString());
address.setText(r.getAddress().toString());
if(r.getType().equals("Sit_Down")){
rButton.check(R.id.sit_down);
}
else if(r.getType().equals(("Delivery"))){
rButton.check((R.id.details));
}
else if(r.getType().equals("Take_Out")){
rButton.check(R.id.take_out);
}
}
};
}
ativity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/restaurants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
<TableLayout
android:id="#+id/details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:stretchColumns="1">
<TableRow>
<TextView android:text="Name:" />
<AutoCompleteTextView android:id="#+id/name" />
</TableRow>
<TableRow>
<TextView android:text="Address:" />
<AutoCompleteTextView android:id="#+id/addr" />
</TableRow>
<TableRow>
<TextView android:text="Date:" />
<EditText android:id="#+id/date"
android:clickable="true"
android:editable="false"/>
</TableRow>
<TableRow>
<TextView android:text="Type:" />
<RadioGroup android:id="#+id/types">
<RadioButton
android:id="#+id/take_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take-Out" />
<RadioButton
android:id="#+id/sit_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sit-Down" />
<RadioButton
android:id="#+id/delivery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delivery" />
</RadioGroup>
</TableRow>
<TableRow>
<TextView android:text="Note:" />
<EditText android:id="#+id/note"/>
</TableRow>
<Button
android:id="#+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save" />
</TableLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
Log
12-07 03:56:24.774 1640-1665/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
12-07 03:56:29.761 2885-2890/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
12-07 03:56:29.764 2885-2890/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
12-07 03:56:30.059 2885-2890/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
The reason for the menu not displaying at the top is because I am extending TabActivity instead of AppCompatActivity.
This is my code below
1) This is Class with getter and setter methods + extension of base adapter
package virtual.mall;
import java.util.List;
import virtual.mall.Salt_page_ada.saltlist_holder;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
class Order1_cls {
String o1_it_name,o1_it_count;
int o1_it_cost,o1_it_qty;
Boolean o1isselect=false;
public Order1_cls(String o1_it_name,String o1_it_count,int o1_it_qty,int o1_it_cost){
super();
this.o1_it_name = o1_it_name;
this.o1_it_count=o1_it_count;
this.o1_it_qty=o1_it_qty;
this.o1_it_cost = o1_it_cost;
this.o1isselect=o1isselect;
}
public String getO1_it_name() {
return o1_it_name;
}
public void setO1_it_name(String o1_it_name) {
this.o1_it_name = o1_it_name;
}
public String getO1_it_count() {
return o1_it_count;
}
public void setO1_it_count(String o1_it_count) {
this.o1_it_count = o1_it_count;
}
public int getO1_it_cost() {
return o1_it_cost;
}
public void setO1_it_cost(int o1_it_cost) {
this.o1_it_cost = o1_it_cost;
}
public int getO1_it_qty() {
return o1_it_qty;
}
public void setO1_it_qty(int o1_it_qty) {
this.o1_it_qty = o1_it_qty;
}
public Boolean getO1isselect() {
return o1isselect;
}
public void setO1isselect(Boolean o1isselect) {
this.o1isselect = o1isselect;
}
}
public class Order1_page extends ArrayAdapter<Order1_cls> {
private List <Order1_cls> order1list;
private Context context;
public Order1_page(List<Order1_cls> order1list, Context context) {
super(context, R.layout.order1listref,order1list);
this.order1list=order1list;
this.context=context;
}
public static class Order1list_holder{
public TextView o1_name;
public TextView o1_count;
public TextView o1_qty;
public TextView o1_cost;
public CheckBox o1chkbx;
}
public View getView(int pos,View con_view,ViewGroup parent){
View v=con_view;
Order1list_holder hold=new Order1list_holder();
if(con_view==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.order1listref,null);
hold.o1_name=(TextView)v.findViewById(R.id.o1_tv_name);
hold.o1_count=(TextView)v.findViewById(R.id.o1_tv_count);
hold.o1_qty=(TextView)v.findViewById(R.id.o1_tv_qty);
hold.o1_cost=(TextView)v.findViewById(R.id.o1_tv_cost);
hold.o1chkbx=(CheckBox)v.findViewById(R.id.o1_cBox);
hold.o1chkbx.setOnCheckedChangeListener((Order1class) context);
}
else{
hold=(Order1list_holder)v.getTag();
}
Order1_cls o1= order1list.get(pos);
//hold.o1_name.setText(o1.getO1_it_name());
hold.o1_count.setText(o1.getO1_it_count());
hold.o1_qty.setText(" "+o1.getO1_it_qty());
hold.o1_cost.setText(" " + o1.getO1_it_cost());
hold.o1chkbx.setChecked(o1.o1isselect);
hold.o1chkbx.setTag(o1);
return v;
}
}
2) This is code for main class extending the activity with handlers
i have written the code for deletion below but it shows an exceptio
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class Order1class extends Activity implements android.widget.CompoundButton.OnCheckedChangeListener {
ListView lv;
ArrayList<Order1_cls> order1list; //class name in ref java file
Order1_page o1adapter; // ref xml name
ArrayList<Integer> positionslist;
ImageButton addc,delbtn;
protected Object posi;
final Context context = this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order1pageclass);
positionslist=new ArrayList<Integer>();
lv=(ListView)findViewById(R.id.order1class_listv); //listview id in main layout
disp_ord1list();
}
private void disp_ord1list() {
// TODO Auto-generated method stub
order1list =new ArrayList<Order1_cls>();
order1list.add(new Order1_cls("Rice(basmati)","1kg packet",3,450));
order1list.add(new Order1_cls("Lentils(finegrade)","2kg packet",2,500));
order1list.add(new Order1_cls("Colgate","5kg packet",3,60));
order1list.add(new Order1_cls("cereal","1kg packet",3,60));
order1list.add(new Order1_cls("surfexcel","2kg packet",2,40));
order1list.add(new Order1_cls("vim","200gms Bar",1,25));
order1list.add(new Order1_cls("Flour","5kg packet",1,300));
o1adapter=new Order1_page(order1list,this);
lv.setAdapter(o1adapter);
}
#Override
public void onCheckedChanged(CompoundButton but_view, boolean o1isselected) {
// TODO Auto-generated method stub
int posi=lv.getPositionForView(but_view);
if(posi !=ListView.INVALID_POSITION){
Order1_cls o1=order1list.get(posi);
o1.setO1isselect(o1isselected);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("remove item ??");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to delete")
.setCancelable(false)
.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
for(int position : positionslist){
order1list.remove(position);
} o1adapter.notifyDataSetChanged();
}
})
.setNegativeButton("add",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Toast.makeText(this,"CLICKED ON " + o1.getO1_it_name()+"of count "+ o1.getO1_it_count()+"cost is "+o1.getO1_it_cost(),Toast.LENGTH_SHORT).show();
}
}
3) order1pageclass.xml file for actual page layout
<?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" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#58ACFA"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order-1 27/3/15"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp" />
</LinearLayout>
<ListView
android:id="#+id/order1class_listv"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_above="#+id/lay1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:background="#FAFAFA" >
</ListView>
<LinearLayout
android:id="#+id/lay1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#58ACFA"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/menu_btn"
android:background="#58ACFA" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.65"
android:src="#drawable/home_btn"
android:background="#58ACFA"
/>
<ImageButton
android:id="#+id/imageButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/cart_btn"
android:background="#58ACFA" />
</LinearLayout>
</RelativeLayout>
4) reference page layout (how each row should look or what it must have )
<?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" >
<TextView
android:id="#+id/o1_tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:text="Rice(Basmati)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/o1_cBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:layout_marginRight="36dp"
android:text="+ Cart" />
<TextView
android:id="#+id/o1_tv_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/o1_tv_name"
android:layout_below="#+id/o1_tv_name"
android:layout_margin="5dp"
android:text="5kg Pack"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/o1_tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_count"
android:layout_alignBottom="#+id/o1_tv_count"
android:layout_margin="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="28dp"
android:layout_toLeftOf="#+id/o1_cBox"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/tvqty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_qty"
android:layout_alignBottom="#+id/o1_tv_qty"
android:layout_margin="5dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/o1_tv_name"
android:text="Qty :"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/o1_tv_cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_qty"
android:layout_alignBottom="#+id/o1_tv_qty"
android:layout_alignRight="#+id/o1_cBox"
android:layout_margin="5dp"
android:text="450 "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
</RelativeLayout>
In your onCheckedChanged() method save the positions in a list. and when button is clicked iterate through the list and delete them from the adapter list.
The Register Button works well, but the debugger doesn't run into the setOnItemClickListener onItemClick. If You click on a item, the activity for editing the record should be launched.
package at.bomsbg.MindX;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import at.bomsbg.MindX.sqlite.helper.MindXopenHelper;
import at.bomsbg.MindX.sqlite.helper.MindXtableAdapter;
public class Activity_cardmanager extends Activity {
MindXtableAdapter mindxtableadapt;
MindXopenHelper openHelper;
ListView nameList;
Button registerBtn;
Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardmanager);
nameList = (ListView) findViewById(R.id.title);
registerBtn = (Button) findViewById(R.id.btn_register);
mindxtableadapt = new MindXtableAdapter(this);
String[] from = { MindXopenHelper.title, MindXopenHelper.detail,
MindXopenHelper.active };
int[] to = { R.id.tv_title, R.id.tv_detail, R.id.tv_active };
cursor = mindxtableadapt.queryName();
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this,
R.layout.row, cursor, from, to);
nameList.setAdapter(cursorAdapter);
nameList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> tobjParent, View tobjView,
int tintPosition, long tlngid) {
Bundle passdata = new Bundle();
Cursor listCursor = (Cursor) tobjParent
.getItemAtPosition(tintPosition);
int nameId = listCursor.getInt(listCursor
.getColumnIndex(MindXopenHelper.KEY_ID));
passdata.putInt(MindXopenHelper.KEY_ID, nameId);
Intent passIntent = new Intent(Activity_cardmanager.this,
Activity_edit_mindxtables.class);
Toast.makeText(getApplicationContext(),
Integer.toString(nameId), 500).show();
passIntent.putExtras(passdata);
startActivity(passIntent);
}
});
registerBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent registerIntent = new Intent(Activity_cardmanager.this,
Activity_MindXtablesRecord.class);
startActivity(registerIntent);
}
});
}
#Override
public void onResume() {
super.onResume();
cursor.requery();
}
}
activity_Cardmanager.html
<LinearLayout 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:orientation="vertical" >
<ListView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
<Button
android:id="#+id/btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/register" />
</LinearLayout>
row.xml
I add the item clickable for the textfield. I think that is not realy necesarry.
<?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="wrap_content"
android:clickable="true"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:width="100dp" />
<TextView
android:id="#+id/tv_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:width="100dp" />
<CheckBox
android:id="#+id/tv_active"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp" />
</LinearLayout>
You have focusable/clickable items in your list view item - the checkbox.
Option 1 - Set the android:descendantFocusability="blocksDescendants" flag to your ListView and you should have fired the onItemClickListener.
Option 2 - In your Adapter you can set an onClickListener on the entire list view item object, and handle it from there.
the Problem of my solution was on row.xml
again thanX on all:
row.xml
<LinearLayout
android:clickable="true" (removed)
<TextView
android:id="#+id/tv_title"
android:onClick="Title" (added)
android:clickable="true" (added)
android:focusable="true" (added)
on my Activity_cardmanager I inserted following code after nameList.setAdapter...
nameList.setClickable(true); // 2015-04-14
nameList.setFocusable(true); // 2015-04-14
nameList.setItemsCanFocus(true); // 2015-04-14
setViewItemListener();
.
.
.
public void setViewItemListener() {
nameList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> tobjParent, View tobjView, int tintPosition, long tlngid) {
Bundle passdata = new Bundle();
// Cursor listCursor = (Cursor) tobjParent.getItemAtPosition(tintPosition);
Cursor listCursor = (Cursor) nameList.getItemAtPosition(tintPosition); //2015-04-15
int nameId = listCursor.getInt(listCursor
.getColumnIndex(MindXopenHelper.KEY_ID));
passdata.putInt(MindXopenHelper.KEY_ID, nameId);
Intent passIntent = new Intent(Activity_cardmanager.this,
Activity_edit_mindxtables.class);
Toast.makeText(getApplicationContext(),
Integer.toString(nameId), Toast.LENGTH_LONG).show();
passIntent.putExtras(passdata);
startActivity(passIntent);
}
});
}
the returnValue is true, but that is another story.
I just want to know if this is possible since first. I have created a custom listView based on the tutorial I read from Sai Geetha. Well it works perfectly on my app except that it needs to extend ListActivity instead of FragmentActivity. Now I'm having a hard time configuring and adding a dialog for this since I need to apply a fragment dialog and I can't use the getFragmentManager() since I'm not working with the FragmentActivity. Is there's another way I can do to work on this without sacrificing the ListActivity? Thanks!
Here's my code so far
XML:
conversation_list_view
<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/android:list"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="20dp"/>
</LinearLayout>
group_screen
<?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"
android:background="#color/white">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#drawable/action_bar_separator"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Group Name"
android:id="#+id/txt_group_name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#color/dark_gray"
android:shadowColor="#color/dark_shadow"
android:shadowRadius="1"
android:shadowDy="1"/>
<Button
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/btn_back"
android:background="#drawable/btn_navigate_back"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<Button
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/btn_information"
android:background="#drawable/btn_information"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Conversations"
android:id="#+id/textView2"
android:textColor="#color/holo_light_blue"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="340dp"
>
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.mark.exercise.ListViewFragment"
android:id="#+id/fragment"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="42dp"
android:text="Ask something"
android:id="#+id/btn_ask_question"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textSize="15dp"/>
</LinearLayout>
</LinearLayout>
Java
package com.mark.exercise;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* Created by pc on 9/24/13.
*/
public class GroupActivity extends FragmentActivity {
Button information, back, new_topic;
ListView conversations;
TextView group_name;
String name, group_description, group_administrator,image_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.group_screen);
Intent intent = getIntent();
name = intent.getStringExtra("group_name");
group_description = intent.getStringExtra("group_description");
group_administrator = intent.getStringExtra("group_administrator");
image_id = intent.getStringExtra("image_id");
information = (Button)findViewById(R.id.btn_information);
back = (Button)findViewById(R.id.btn_back);
new_topic = (Button)findViewById(R.id.btn_ask_question);
group_name = (TextView)findViewById(R.id.txt_group_name);
group_name.setText(name);
information.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GroupActivity.this, GroupInformationActivity.class);
intent.putExtra("group_name",name);
intent.putExtra("group_description",group_description);
intent.putExtra("group_administrator",group_administrator);
intent.putExtra("image_id",image_id);
startActivity(intent);
GroupActivity.this.overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
});
new_topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showCreateNewTopicDialog();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void showCreateNewTopicDialog() {
FragmentManager fm = getSupportFragmentManager();
DialogFragmentCreateGroup createGroup = new DialogFragmentCreateGroup();
createGroup.show(fm, "create_group");
}
#Override
public void onBackPressed(){
super.onBackPressed();
overridePendingTransition(R.anim.in_from_right,R.anim.out_to_left);
}
}
List Fragment
package com.mark.exercise;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created by pc on 9/27/13.
*/
public class ListViewFragment extends ListFragment {
final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.conversations_list_view,
container, false);
setListView set_list = new setListView();
set_list.start();
return view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
//super.onListItemClick(l, v, position, id);
Intent intent = new Intent(getActivity(), ConversationActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
private class setListView extends Thread {
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
setConversations();
}
});
}
}
private void setConversations(){
list.clear();
SimpleAdapter adapter = new SimpleAdapter(
getActivity(),
list,
R.layout.custom_list_main_conversations,
new String[] {"message","date", "reply_count", "stars_count"},
new int[] {R.id.txt_conversation_message,R.id.txt_topic_date, R.id.txt_no_of_reply, R.id.txt_no_of_stars}
);
for(int ctr=0;ctr<=5;ctr++){
Random randomGenerator = new Random();
HashMap<String,String> item_list = new HashMap<String,String>();
item_list.put("message", "This is the conversation number "+(ctr+1)+" and this topic is just a dummy data.");
item_list.put("date", "0"+(ctr+1)+"/0"+(ctr+2)+"/2013 "+(ctr+1)+":00:am");
item_list.put("reply_count", String.valueOf(ctr+randomGenerator.nextInt(10)));
item_list.put("stars_count", String.valueOf(ctr+randomGenerator.nextInt(10)));
list.add(item_list);
}
android.app.ListFragment lf = new android.app.ListFragment();
lf.setListAdapter(adapter);
}
}
You can use ListFragment inside FragmentActivity instead of using a ListActivity.
I have two classes and a XML. The first one creates an ListApter full of cocktail names like bloody mary,margarita, ect. The second class is set up so I can change the TextView and an Image displayed in the XML. I'm having difficulty trying to pass the item that I'v pressed in the ListAdapter into the CocktailDetail class to change the values of the TextView and the Image. Can anybody help? It runs but opens Bloody mary for every item selected in the list.
Menu class
package com.drunktxtapp;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity {
String classes[] = { "Bloody_Mary", "Capirinha", "Cosmopolitan",
"Cuba_Libre", "Daiquiri", "Mai_Tai", "Manhattan", "Margarita",
"Martini", "Mint_Julep", "Mojito", "Old_Fashoned", "Pina_Colada",
"Screwdriver", "Singapore_Sling", "Tom_Collins", "Whiskey_Sour",
"White_Russian" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
;
Intent ourIntent = new Intent(Menu.this, CocktailDetail.class);
ourIntent.putExtra("cocktail_name","bloodymary");
startActivity(ourIntent);
};
}
CocktailDetail class
package com.drunktxtapp;
import android.net.Uri;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.widget.TextView;
import android.view.View;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class CocktailDetail extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cocktaildetail);
ImageView imageView1 = (ImageView)findViewById(R.id.imageCocktail);
imageView1.setImageDrawable(getResources().getDrawable(R.drawable.bloodymary));
Button b1 = (Button) findViewById(R.id.buttonYoutube);
TextView t1 = (TextView)findViewById(R.id.textCocktailName);
String cocktailName = "Bloody Mary";
t1.setText(cocktailName);
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=Alt-ehDc3fc")));
}
});
}
}
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"
android:background="#drawable/beer"
android:id="#+id/cocktailDetail" >
<TextView
android:id="#+id/textCocktailName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Cocktail Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/imageCocktail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/bloodymary" />
<TextView
android:textStyle="bold"
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Ingredients"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textIngredients"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Insert txt here"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="2dp"
android:text="Preparation"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textPrepration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Insert txt here"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<Button
android:id="#+id/buttonYoutube"
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text="YouTube Clip"
android:textSize="20dp" />
</LinearLayout>
In Menu class, you are passing hard coded string :
ourIntent.putExtra("cocktail_name",**"bloodymary"**);
Change this to the value retrieved from the ListView :
String selectedFromList =(String) (l.getItemAtPosition(position));
ourIntent.putExtra("cocktail_name",selectedFromList);
Also in Cocktail Class, OnCreate, again you are setting text to hardcoded string. Using Bundle, retrieve the value and then setText;
Bundle bundle = getIntent().getExtras();
//Extract the data…
String name = bundle.getString(“cocktail_name”);
TextView t1 = (TextView)findViewById(R.id.textCocktailName);
t1.setText(name);
Try this in Menu activity:
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// here you get the Item selected using position
Intent i = new Intent(MenuActivity.this, CocktailDetails.class);
i.putExtra("title", your_title_cocktail);
startActivity(i);
}
});
in the DetailActivity
protected void onCreate(Bundle savedInstanceState) {
Intent i = getIntent();
---
}
give a look here and here.