I want to make a list of restaurants and have radiobutton besides each name. so i have made two xml files. In the first one there is a listview and another there is a single radioButton.
Now i want to set the onClick listener on each radioButton.Please suggest me about how to do it. I am posting my code below.
MainActivity.java
package com.example.radiogroup;
import java.util.ArrayList;
import java.util.HashMap;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private ArrayList<HashMap<String,Object>> data;
private ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView)findViewById(R.id.listView1);
data=new ArrayList<HashMap<String, Object>>();
prepareListData();
adapter = new ListAdapter(this,data);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
RadioButton rb=(RadioButton)findViewById(R.id.radioButton1);
{
if(position==0)
{
Toast.makeText(getApplicationContext(), "Move forward",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void prepareListData()
{
HashMap<String,Object> row1=new HashMap<String,Object>();
row1.put("ID",1 );
row1.put("NAME","Taj Mahal");
data.add(row1);
HashMap<String,Object> row2=new HashMap<String,Object>();
row2.put("ID",2 );
row2.put("NAME","Agra Fort");
data.add(row2);
HashMap<String,Object> row3=new HashMap<String,Object>();
row3.put("ID",3 );
row3.put("NAME","Ram Baugh");
data.add(row3);
HashMap<String,Object> row4=new HashMap<String,Object>();
row4.put("ID",4 );
row4.put("NAME","Panch Mahal");
data.add(row4);
HashMap<String,Object> row5=new HashMap<String,Object>();
row5.put("ID",5 );
row5.put("NAME","Musamman Burj");
data.add(row5);
}
class ListAdapter extends BaseAdapter
{
private Context context;
private ArrayList<HashMap<String,Object>> list;
public ListAdapter(Context context,ArrayList<HashMap<String,Object>> list){
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row,null,false);
holder.rb = (RadioButton) convertView.findViewById(R.id.radioButton1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.rb.setText(list.get(position).get("NAME").toString());
return convertView;
}
class ViewHolder
{
RadioButton rb;
}
}
}
Use it in ListAdapter-
holder.rb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "" + position,
Toast.LENGTH_LONG).show();
}
});
Related
I saw a tutorial on youtube showing how you can add data to sqlLite db and then display these data to a ListView Video.
After doing that... I applied DragSortListView to my listview... but everytime I drag a row. This error keeps on coming and I couldn't solve it :
FATAL EXCEPTION: main
Process: com.example.justi.ricksonbar, PID: 29157
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.justi.ricksonbar.ProductAdapter.getItem(ProductAdapter.java:49)
at com.example.justi.ricksonbar.BackgroundTask$1.drop(BackgroundTask.java:91)
at com.mobeta.android.dslv.DragSortListView.dropFloatView(DragSortListView.java:1501)
at com.mobeta.android.dslv.DragSortListView.access$1200(DragSortListView.java:59)
at com.mobeta.android.dslv.DragSortListView$DropAnimator.onStop(DragSortListView.java:1293)
at com.mobeta.android.dslv.DragSortListView$SmoothAnimator.run(DragSortListView.java:1192)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Here's my ProductAdapter.java¨
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ProductAdapter extends ArrayAdapter{
List list = new ArrayList();
public ProductAdapter(Context context,int resource) {
super(context, resource);
}
public void add(Product object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ProductHolder productHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product_list, parent, false);
productHolder = new ProductHolder();
productHolder.tx_name = (TextView)row.findViewById(R.id.tvProd_name);
productHolder.tx_price = (TextView)row.findViewById(R.id.tvProd_price);
productHolder.tx_type = (TextView)row.findViewById(R.id.tvProd_type);
row.setTag(productHolder);
}else{
productHolder = (ProductHolder) row.getTag();
}
Product product = (Product) getItem(position);
productHolder.tx_name.setText(product.getName().toString());
productHolder.tx_price.setText(Double.toString(product.getPrice()));
productHolder.tx_type.setText(product.getType().toString());
return row;
}
static class ProductHolder{
TextView tx_name, tx_price, tx_type;
}
}
and my BackgroundTask.java (where I put DragSortListView methods)
import android.app.Activity;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class BackgroundTask extends AsyncTask<String, Product, String> {
Context ctx;
ProductAdapter productAdapter;
Activity activity;
DragSortListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseHelper dHelper = new DatabaseHelper(ctx);
if (method.equals("add_info")){
String name = params[1];
double price = Double.parseDouble(params[2]);
String type = params[3];
SQLiteDatabase db = dHelper.getWritableDatabase();
//Call method of insertion
dHelper.addInformations(db, name, price, type);
return "One row is inserted....";
}else if (method.equals("get_info")){
listView = (DragSortListView)activity.findViewById(R.id.display_listview);
SQLiteDatabase db = dHelper.getReadableDatabase();
Cursor cursor = dHelper.getInformations(db);
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
String name, type;
double price;
while (cursor.moveToNext()){
name = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.NAME));
price = cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.PRICE));
type = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.TYPE));
Product product = new Product(name, price, type);
publishProgress(product);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Product... values) {
productAdapter.add(values[0]);
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
productAdapter.remove(productAdapter.getItem(which));
}
};
#Override
protected void onPostExecute(String result) {
if (result.equals("get_info")){
listView.setAdapter(productAdapter);
listView.setDropListener(onDrop);
listView.setRemoveListener(onRemove);
DragSortController controller = new DragSortController(listView);
controller.setRemoveEnabled(false);
controller.setSortEnabled(true);
controller.setDragInitMode(1);
listView.setFloatViewManager(controller);
listView.setOnTouchListener(controller);
listView.setDragEnabled(true);
}else{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
}
Please help me. Thank you so much
You are trying to fetch item before adding any element in a adapter.
#Override
public void drop(int from, int to)
{ // Adapter is Created here
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
// here you are trying to get item which must throw indexoutofbounds
// because you didn't added anything yet
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
According to your add method of your adapter will add elements in Adapter.
public void add(Product object) {
list.add(object);
super.add(object);
}
Use Cursor Adapter, it is more efficient:
https://guides.codepath.com/android/Populating-a-ListView-with-a-CursorAdapter
I am using custom listViewAdapter class and I want to check one box in a single row, but it is checking multiple checks in multiple rows which is not my requirement. Please tell me how can I resolve it.
CourseActivity.java
package com.technerdshub.vusocial.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.technerdshub.vusocial.DBHelper;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.Models.User;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class CourseActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView list;
EditText editsearch;
ArrayList arrayList = new ArrayList();
CourseViewAdapter adapter;
Course courseObject;
boolean isChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_activity);
List<Course> courseList;
DBHelper db = new DBHelper(this);
courseList = db.getAllCourses();
list = (ListView) findViewById(R.id.listview1);
for (Course c : courseList) {
arrayList.add(c);
}
adapter = new CourseViewAdapter(this, arrayList);
adapter.courseActivity = this;
list.setAdapter(adapter);
editsearch = (EditText) findViewById(R.id.searchF);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
User user = User.getInstance();
saveUserOnParse(user);
}
private void saveUserOnParse(User user) {
ParseObject parseUser = new ParseObject("UserData");
parseUser.put("name", user.getName());
parseUser.put("vuId", user.getVuId());
parseUser.put("studyProgram", user.getStudyProgram());
parseUser.put("facebookId", user.getFacebookId());
parseUser.put("facebookEmail", user.getFacebookEmail());
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Intent i = new Intent(getContext(), StudentDashboardActivity.class);
//// i.putExtra("E-mail", "abc");
// startActivity(i);
} else {
Toast temp = Toast.makeText(CourseActivity.this, "Data is not saved.", Toast.LENGTH_SHORT);
temp.show();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 4
if (requestCode == 2) {
courseObject = (Course) data.getExtras().getSerializable("SelectedCourse");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) view.findViewById(R.id.checkBox);
// TextView tv = (TextView) v.findViewById(R.id.textView1);
cb.performClick();
if (cb.isChecked()) {
// checkedValue.add(tv.getText().toString());
} else if (!cb.isChecked()) {
// checkedValue.remove(tv.getText().toString());
}
}
}
CourseViewAdapter.java
package com.technerdshub.vusocial.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Saroosh on 7/16/2016.
*/
public class CourseViewAdapter extends BaseAdapter {
protected CourseActivity courseActivity;
Context mContext;
LayoutInflater inflater;
private List<Course>worldpopulationlist=null;
private ArrayList<Course> arraylist;
public CourseViewAdapter(Context context, List<Course>worldpopulationlist){
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Course>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView courseCode;
TextView courseName;
CheckBox checkBox;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public Course getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.c_list_item, null);
// Locate the TextViews in listview_item.xml
holder.courseName = (TextView) view.findViewById(R.id.course_name);
holder.courseCode = (TextView) view.findViewById(R.id.course_code);
holder.checkBox= (CheckBox) view.findViewById(R.id.checkBox);
// holder.duration = (TextView) view.findViewById(R.id.program_duration);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.courseName.setText(worldpopulationlist.get(position).getCourseName());
holder.courseCode.setText(worldpopulationlist.get(position).getCourseCode());
//holder.duration.setText(worldpopulationlist.get(position).getDuration());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, CourseActivity.class);
// Pass all data ran
intent.putExtra("SelectedCourse", worldpopulationlist.get(position));
// Pass all data country
courseActivity.setResult(2,intent);
courseActivity.finish();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (Course wp : arraylist)
{
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Write all your checkbox logic inside you adapter getView method. That will work .
I want to be able to click on the "username" which will lead me to a new class - SetMed.java. Along with the username, i would like it's ID's to be passed on as well. I have tried using Intent but it does not work. Any help is greatly appreciated.
This is my MainActivity.java
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListView_CheckBoxActivity extends Activity {
//Adapter
CheckboxAdapter listItemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Buttons and incident response
Button getValue=(Button)findViewById(R.id.get_value);
getValue.setOnClickListener(listener);
//listview
ListView list = (ListView) findViewById(R.id.list);
//Array list to store the data
ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
String []name={"Diabetes","example","example","example","example"};
String []id={"Insulin, Glucagon, Prandin","example","example","example","example"};
for(int i=0;i<5;i++)
{
HashMap<String, Object>
map=new HashMap<String, Object>();
map.put("friend_image", R.drawable.icon);
map.put("friend_username", name[i]);
map.put("friend_id", id[i]);
map.put("selected", false);
//Add data
listData.add(map);
}
//Adapter
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
}
//Incident Response
OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(ListView_CheckBoxActivity.this, SetMed.class);
boolean[] array = new boolean[5];
array[0] = CheckboxAdapter.isChecked();
intent.putExtra("status", array);
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Medicine Selected:";
for(int j=0; j<listItemAdapter.getCount(); j++)
{
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null)
{
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
options+="\n"+username;
}
}
//Display selection
startActivity(intent)
}
};
}
This is my CheckBoxAdapter class.
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
//Record checkbox state
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
// Constructor
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData)
{
this.context = context;
this.listData = listData;
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
// Rewrite View
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
state.put(position, isChecked);
} else
{
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
public static boolean isChecked() {
// TODO Auto-generated method stub
return false;
}
Class SetMed
public class SetMed extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_set_med);
TextView diabetes = (TextView) findViewById(R.id.diabetes);
Bundle bundle = this.getIntent().getExtras();
if (bundle.getBoolean("Diabetes", false)) {
diabetes.setText("Diabetes");
} else {
diabetes.setText("");
}
}
}
I want To Create my custom baseadapter So I try the following :
MainActivity.java
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.util.ArrayList;
public class SignupActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
String [] arr = {"USA","Canda","Germany","Italy"};
Spinner S1 = (Spinner) findViewById(R.id.Spinner_Signup);
CustomCountryAdpater adapter = new CustomCountryAdpater(this, arr);
S1.setAdapter(adapter);
}
}
CustomCountryAdpater.java
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import java.util.ArrayList;
import android.widget.TextView;
public class CustomCountryAdpater extends BaseAdapter {
public Context con;
//public ArrayList<Country> tempList;
String [] arr;
public LayoutInflater myInflater;
public CustomCountryAdpater (Context C,String [] arr)
{
this.con = C;
this.arr = arr;
this.myInflater = (LayoutInflater) C.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return this.arr.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return this.arr[arg0];
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
if (arg1==null)
{
arg1 = myInflater.inflate(android.R.layout.simple_list_item_1, arg2, false);
TextView TT = (TextView) arg1.findViewById(android.R.id.text1);
TT.setText(this.arr[arg0]);
}
return arg1;
}
}
when I click on the spinner for first time I got the correct list :
but if I choose Germany, For example and click on the spinner again I get the following list that have no Germany !!!
can anyone told me Why ?!!!
Because you conditionally update text. arg1 you use might be an old, cached View.
Move these lines after if:
TextView TT = (TextView) arg1.findViewById(android.R.id.text1);
TT.setText(this.arr[arg0]);
i try to make two fragments in honeycomb, list and gridview.When i clicked the list-item, the GridView successfully displayed.but,the list was disappear.GridView should be displayed beside the list.here's my code:
FragmentTestActivity.java
package com.android.tabgrid;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentTestActivity extends FragmentActivity implements
OnItemClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.list_icon);
ArrayAdapter<String> yoyo = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,new String[] {
"Traffic",
"Forum",
"Promo",
"Others"
});
lv.setAdapter(yoyo);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
Fragment f = new TestFragment(position+1);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.the_frag,f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
TestFragment.java
package com.android.tabgrid;
import com.android.content.GridView1;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class TestFragment extends Fragment {
private int magznumber;
public TestFragment() {
}
public TestFragment(int position) {
this.magznumber = position;
}
#Override
public void onCreate(Bundle saved) {
super.onCreate(saved);
if (null != saved) {
magznumber = saved.getInt("magznumber");
}
}
#Override
public void onSaveInstanceState(Bundle toSave) {
toSave.putInt("magznumber", magznumber);
}
/**
* Make a grid to view the magazines
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) {
Context c = getActivity().getApplicationContext();
LinearLayout l = new LinearLayout(c);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.FILL_PARENT, 0);
l.setLayoutParams(params);
ImageView i = new ImageView(c);
switch(magznumber){
case 1:
Intent i1 = new Intent(getActivity(), GridView1.class);
startActivity(i1);
break;
case 2:
i.setImageResource(R.drawable.lfymag);
break;
case 3:
i.setImageResource(R.drawable.ffymag);
break;
}
l.addView(i);
return l;
}
}
GridView1.java
package com.android.content;
import com.android.tabgrid.FragmentTestActivity;
import com.android.tabgrid.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.android.tabgrid.TestFragment;
public class GridView1 extends FragmentActivity{
Integer[] img = {
R.drawable.btn_spot_u,
R.drawable.btn_traffic_u,
R.drawable.btn_forum_u,
R.drawable.btn_promo_u
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_1);
GridView gV = (GridView)findViewById(R.id.grid1);
gV.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
public ImageAdapter(Context c) {
ctx = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return img.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imgView;
if(v == null) {
imgView = new ImageView(ctx);
imgView.setLayoutParams(new GridView.LayoutParams(85,85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(5, 5, 5, 5);
} else {
imgView = (ImageView) v;
}
imgView.setImageResource(img[position]);
return imgView;
}
}
}
please help me and repair mycode.big thanks