Click on search item inside edittext redirect on wrong activity, it doesn't open the activity associated with it. It opening other activities that are associated with other listitems but not that i am clicking one.
Here is my complete code:
public class Tabtwo extends Activity implements OnItemClickListener {
ListView listView;
TextView txt;
ArrayAdapter<String> adapter;
// Search EditText
EditText edtSearch;
// Array of strings storing country names
String[] countries = new String[] { "Admin Cost", "Affinity Diagram",
"Analyse", "Apprasal Costs", "Assessment of Stakeholders",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[] { R.drawable.admin, R.drawable.affinity,
R.drawable.analysis, R.drawable.appraisal, R.drawable.assessment,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabtwo);
// Each row in the list stores country name, currency and flag
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 4; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("txt", countries[i]);
hm.put("flag", Integer.toString(flags[i]));
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag", "txt" };
// Ids of views in listview_layout
int[] to = { R.id.flag, R.id.txt };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = (ListView) findViewById(R.id.listview);
edtSearch = (EditText) findViewById(R.id.Search_box);
txt = (TextView) findViewById(R.id.txt);
listView.setOnItemClickListener(this);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if (position == 0) {
Intent int0 = new Intent(getApplicationContext(), Admincost.class);
startActivity(int0);
}
if (position == 1) {
Intent int1 = new Intent(getApplicationContext(), Affinity.class);
startActivity(int1);
}
if (position == 2) {
Intent int2 = new Intent(getApplicationContext(), Analyse.class);
startActivity(int2);
}
if (position == 3) {
Intent int3 = new Intent(getApplicationContext(),
ApprasalCosts.class);
startActivity(int3);
}
if (position == 4) {
Intent int1 = new Intent(getApplicationContext(), Assessment.class);
startActivity(int1);
} }
}
}
Here is my tabtwo xml file.
<?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" >
<EditText
android:id="#+id/Search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Search a Item from ListView"
android:inputType="textVisiblePassword" />
/>
<TextView
android:id="#+id/List_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dip"
android:textSize="17sp"
android:textStyle="bold" />
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-50dp" />
</LinearLayout>
Here is listview_layout.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="horizontal" >
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="21dp" />
</LinearLayout>
Replace your onItemClick method with below and try.. Hope it works..
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
TextView tv = (TextView) arg1.findViewById(R.id.txt);
String str = tv.getText().toString().trim();
if (str.equals(countries[0])) {
Intent int0 = new Intent(Tabtwo.this, Admincost.class);
startActivity(int0);
}else if(str.equals(countries[1])) {
Intent int1 = new Intent(Tabtwo.this, Affinity.class);
startActivity(int1);
}else if(str.equals(countries[2])) {
Intent int2 = new Intent(Tabtwo.this, Analyse.class);
startActivity(int2);
}else if(str.equals(countries[3])) {
Intent int3 = new Intent(Tabtwo.this, ApprasalCosts.class);
startActivity(int3);
}else if(str.equals(countries[4])) {
Intent int1 = new Intent(Tabtwo.this, Assessment.class);
startActivity(int1);
}
}
Add this code to your TextView as well as to ImageView
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and for ItemClick you can use the answer of Tamilan
I meet the same question with you. Try the following one:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
//(String) getListAdapter().getItem(position);
String city_id=map.get( (String) adapter.getItem(position) );
Toast.makeText(getApplicationContext(),city_id, Toast.LENGTH_SHORT).show();
Intent i=new Intent(MainActivity.this,DetailActivity.class);
i.putExtra("city_id",city_id);
startActivity(i);
}
});
Related
hello guys I'm looking how to make my ListView clickable , i searched in the net but i haven't found the right answer , and this is my code please help me
`public class acceuil extends AppCompatActivity {
ListView listView;
int [] movie_poster_resource = {R.drawable.profil};
String[] patient_names;
String[] temps_rendez;
MovieAdapter adapter;
View view;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acceuil);
listView= (ListView)findViewById(R.id.listView);
temps_rendez = getResources().getStringArray(R.array.temps);
patient_names = getResources().getStringArray(R.array.patient_title);
int i=0;
adapter = new MovieAdapter(getApplicationContext(),R.layout.patient_name);
listView.setAdapter(adapter);
for (String titles: patient_names)
{
MovieDataProvider dataProvider = new MovieDataProvider(movie_poster_resource[i],titles,temps_rendez[i]);
adapter.add(dataProvider);
}
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
if (id == 0)
startActivity(new Intent(this, patient_from_listview.class));
}
public void open_messagerie (View view){
startActivity(new Intent(this, acceuil.class));
}
public void openn_otification (View view){
startActivity(new Intent(this, acceuil.class));
}
public void opena_parametre (View view){
startActivity(new Intent(this, acceuil.class));
}
public void open_calcule (View view){
startActivity(new Intent(this, acceuil.class));
}
}`
You'd call listView.setOnItemClickListener(OnItemClickListener). That sets the class to be called when an item is clicked. It looks like you've already implemented the onItemClicked function, this will hook it up.
This is how you can achieve this
adapter = new MovieAdapter(getApplicationContext(),R.layout.patient_name);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
// HERE YOU CAN MAKE CASES FOR EACH CLICK
}
Here is my code, how to do clickable listview on Android Studio...
MAIN ACTIVICTY CODE
ListView listView;
int mImage[] = {R.drawable.switzerland, R.drawable.canada, R.drawable.japan, R.drawable.usa};
String mTitle[] = {"Switzerland Title", "Canada Title", "Japan Title", "USA Title"};
String mDescription[] = {"Switzerland is a mountainous Central European country, home to numerous lakes, villages and the high peaks of the Alps.", "Canada is a country in the northern part of North America. Its ten provinces and three territories extend from the Atlantic to the Pacific.", "Japan is an island country in East Asia, located in the northwest Pacific Ocean.", "The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest."};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// for listview settings
listView = findViewById(R.id.listview);
MyAdapter adapter = new MyAdapter(this, mImage, mTitle, mDescription);
listView.setAdapter(adapter);
//listview click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position==0){
Intent intent = new Intent(getApplicationContext(), Switzerland.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[0]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[0]);
intent.putExtra("description", mDescription[0]);
intent.putExtra("position", ""+0);
startActivity(intent);
}else if (position==1){
Intent intent = new Intent(getApplicationContext(), Canada.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[1]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[1]);
intent.putExtra("description", mDescription[1]);
intent.putExtra("position", ""+1);
startActivity(intent);
}else if (position==2){
Intent intent = new Intent(getApplicationContext(), Japan.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[2]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[2]);
intent.putExtra("description", mDescription[2]);
intent.putExtra("position", ""+2);
startActivity(intent);
}else if (position==3){
Intent intent = new Intent(getApplicationContext(), USA.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[3]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[3]);
intent.putExtra("description", mDescription[3]);
intent.putExtra("position", ""+3);
startActivity(intent);
}
}
});
}
// for listview adapter
class MyAdapter extends ArrayAdapter<String> {
Context context;
int sImage[];
String sTitle[];
String sDescription[];
MyAdapter (Context c, int image[], String title[], String description[]){
super(c, R.layout.main_page_row, R.id.main_page_title, title);
this.context = c;
this.sImage = image;
this.sTitle = title;
this.sDescription = description;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= layoutInflater.inflate(R.layout.main_page_row, parent, false);
ImageView imageView = view.findViewById(R.id.main_page_image);
TextView titleText = view.findViewById(R.id.main_page_title);
TextView descriptionText = view.findViewById(R.id.main_page_description);
imageView.setImageResource(sImage[position]);
titleText.setText(sTitle[position]);
descriptionText.setText(sDescription[position]);
return view;
}
}
Here is MAIN ACTIVITY XML Code
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1500dp"
android:orientation="vertical">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Here is MAIN ACTIVITY ROW XML Code
<androidx.cardview.widget.CardView
android:orientation="vertical"
app:cardElevation="5dp"
app:cardCornerRadius="12dp"
android:layout_margin="3dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageID"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/erroricon"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/titleID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/bb_name"
android:textSize="18sp"
android:textColor="#000000"
android:textStyle="bold" />
<TextView
android:id="#+id/descriptionID"
android:text="#string/mp_des"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:ellipsize="end"
android:maxLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Here is Details Page Java Code
ImageView image;
TextView sTitle, sDescription;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_page);
image = findViewById(R.id.details_page_image);
sTitle = findViewById(R.id.details_page_title);
sDescription = findViewById(R.id.details_page_description);
if (position == 0){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 1){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 2){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 3){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
}
The Listview is displaying some rows instead of all items (sometimes, it's displaying nothing), I couldn't understand why this is happenning. It occurs at first run. After that, it works well, with all items from database filled on the screen. I put vertical orientation in my linear layout xml files and wrap_content height. But the problem is not solved.
This is my main activity :
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile1";
private TextView mTextView;
private ListView mListView;
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();
DictionaryDatabase DictionaryDatabase;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
mListView = (ListView) findViewById(R.id.list);
DictionaryDatabase=new DictionaryDatabase(this);
allWordDefinitions=DictionaryDatabase.getAllWords();
Collections.sort(allWordDefinitions, new CustomComparator());
mListView.setAdapter(new BaseAdapter() {
#Override
public View getView(int position, View view, ViewGroup arg2) {
if (view==null) {
view=getLayoutInflater().inflate(R.layout.list_item, arg2, false);
}
TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
textView.setText(allWordDefinitions.get(position).word);
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return allWordDefinitions.size();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Intent intent =new Intent(MainActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", allWordDefinitions.get(position).word);
intent.putExtra("definition", allWordDefinitions.get(position).definition);
startActivity(intent);
}
});
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, WordActivity.class);
this.finish();
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
mTextView.setText(getString(R.string.no_results, new Object[] {query}));
} else {
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
mTextView.setText(countString);
String[] from = new String[] { DictionaryDatabase.KEY_WORD,
DictionaryDatabase.KEY_DEFINITION };
int[] to = new int[] { R.id.word,
R.id.definition };
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.result, cursor, from, to);
mListView.setAdapter(words);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,
String.valueOf(id));
wordIntent.setData(data);
startActivity(wordIntent);
}
});
}
}
public class CustomComparator implements Comparator<WordDefinition> {
#Override
public int compare(WordDefinition p1, WordDefinition p2) {
return p1.word.compareTo(p2.word);
}
}
}
WorDefinition (Array List):
public class WordDefinition {
String word,definition;
public WordDefinition(String word,ArrayList<String> alldefinition) {
this.word=word;
StringBuilder stringBuilder=new StringBuilder();
for (String string : alldefinition) {
stringBuilder.append(string);
}
this.word=stringBuilder.toString();
}
public WordDefinition(String word,String alldefinition) {
this.word=word;
this.definition=alldefinition;
}
}
DictionaryDatabase (snippet)
public ArrayList<WordDefinition> getAllWords() {
ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
SQLiteDatabase database=mDatabaseOpenHelper.getReadableDatabase();
String selectAllQueryString="SELECT * FROM "+FTS_VIRTUAL_TABLE;
Cursor cursor=database.rawQuery(selectAllQueryString, null);
if (cursor.moveToFirst()) {
do {
WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(KEY_WORD)), cursor.getString(cursor.getColumnIndex(KEY_DEFINITION)));
arrayList.add(wordDefinition);
} while (cursor.moveToNext());
}
return arrayList;
}
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:background="#drawable/fundoeua"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<LinearLayout
android:id="#+id/Line1"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:textColor="#FFFFFF"
android:gravity="right"
android:textAlignment="gravity"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="15dp"
android:textStyle="bold"
android:textSize="20sp"
android:text="#string/chamada"
android:background="#color/vermelho"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff0000"
android:dividerHeight="4px"
/>
</LinearLayout>
</RelativeLayout>
list_item.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:background="#drawable/seletor2"
android:orientation="vertical" >
<TextView
android:id="#+id/listItemTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:textColor="#color/preto"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Sometimes height ListView calculate incorrect.
Android: wrap_content is not working with ListView
You can use one adapter and one ListView instead of Two ListViews. Use types for items in this adapter. In this way you can remove wrap_content and set match_parent for height attribute in ListView
I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.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) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_view:-
<?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:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);
In my App i download a list of strings from the web
then i'm using AsyncTask to update the listview on my activity.
at prePostExecute im creating the array adapter(private member)
at doInBackground i download the list and return it
at onPostExecute i set the returned list to the adapter and then connects the listview and the adapter
in my activity i see just 1 blank element(instead of 2 elements) , when i click it i can see the Text but when im not its blank.
also , when my adapter is not android.R.layout.simple_list_1 but android.R.layout.acitiviy_list_item (and 2 other templates) i can see 2 elements with visible text but the text is small and gray
code:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#4CB8FB"
android:gravity="center"
android:text="Search"
android:textColor="#FAFAFA"
android:textSize="40sp" />
</TableRow>
<EditText
android:id="#+id/searchInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_btn_search" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:scrollingCache="true" >
</ListView>
</LinearLayout>
code Behind
public class ProductPickerActivity extends Activity {
private ListView listView;
private EditText inputSearch;
private ArrayAdapter<String> adapter;
private final Integer PRODUCT_REQUEST_ID = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_listview);
inputSearch = (EditText) findViewById(R.id.searchInput);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ProductPickerActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
new InitializeUi().execute(this);
setupUI(findViewById(R.id.parent));
}
private class InitializeUi extends AsyncTask<Object, Void, List<IProduct>> {
#Override
protected void onPreExecute() {
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.activity_list_item, new ArrayList<String>());
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), ProductViewActivity.class);
intent.putExtra("ProductName", itemValue);
startActivityForResult(intent, PRODUCT_REQUEST_ID);
}
});
}
#Override
protected List<IProduct> doInBackground(Object... params) {
// Defined Array values to show in ListView
IProductManager manager = new ProductManager(getApplicationContext());
// download from web
List<IProduct> lst = manager.GetProductList();
return lst;
}
#Override
protected void onPostExecute(List<IProduct> lst) {
String[] values = new String[lst.size()];
Integer i = 0;
for (IProduct p : lst) {
values[i] = p.getName();
i = i + 1;
Log.d("ProductPickerActivity", "Got Values : " + p.getName());
adapter.add(p.getName());
adapter.notifyDataSetChanged();
}
// Assign adapter to ListView
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
listView.refreshDrawableState();
}
}
}
apply the edit code below to onPostExecute hope its work
// Assign adapter to ListView
listView.setAdapter(adapter);
//then add values to adatper
String [] values = new String[lst.size()];
int i =0; //<<-- change to int
for(IProduct p : lst)
{
values[i] = p.getName();
i++;//<-- add +1
Log.d("ProductPickerActivity","Got Values : "+p.getName());
adapter.add(p.getName());
}
//finaly notify adapter data changed
adapter.notifyDataSetChanged();
I have three lists, which contains "root, top and down".
but when I filter the list with "top", and then I click on the list, which appears is the "root". how can I make it a clickable list according to which we filter?
list.java
public class root extends Activity {
EditText edittext;
ListView listview;
private String[] text = { "ROOT", "TOP", "DOWN" };
private int[] image = { R.drawable.root, R.drawable.top, R.drawable.down };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlistview);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if ("ROOT".equals(text[position])) {
Intent myIntent = new Intent(view.getContext(),
root.class);
startActivityForResult(myIntent, 0);
}
if ("TOP".equals(text[position])) {
Intent myIntent = new Intent(view.getContext(),
top.class);
startActivityForResult(myIntent, 0);
}
if ("DOWN".equals(text[position])) {
Intent myIntent = new Intent(view.getContext(),
down.class);
startActivityForResult(myIntent, 0);
}
});
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++) {
if (textlength <= text[i].length()) {
if (edittext
.getText()
.toString()
.equalsIgnoreCase(
(String) text[i].subSequence(0,
textlength))) {
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));
}
});
}
class MyCustomAdapter extends BaseAdapter {
String[] data_text;
int[] data_image;
MyCustomAdapter() {
}
MyCustomAdapter(String[] text, int[] image) {
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image) {
data_text = new String[text.size()];
data_image = new int[image.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount() {
return data_text.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
}
main.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" >
<EditText
android:id="#+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search" >
</EditText>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
listview.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="wrap_content"
android:background="#fff200"
android:gravity="left|center"
android:paddingBottom="5px"
android:paddingLeft="5px"
android:paddingTop="5px" >
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ImageView>
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10px"
android:textColor="#0099CC"
android:textSize="20px"
android:textStyle="bold" >
</TextView>
The problem lies within your onItemClickListener of your ListView:
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if ("ROOT".equals(text[position])) {
Intent myIntent = new Intent(view.getContext(),class);
startActivityForResult(myIntent, 0);
After you have filtered your ListView, your ListView will show only 1 item. When you click this item, the onItemClick will get triggered. Because your clicked item is at the first position of your new filtered ListView, the variable position is 0. The first item in your Array text[] is "ROOT" so the RootActivity will be started.
Solution
Ask your adapter which View you have clicked and compare that to a String:
Inside your onItemClicked(..):
View selectedView = yourAdapter.getItemAtPosition(position)
TextView myText = (TextView) selectedView.findViewById(R.id.TextView01).getText()
if(myText.equals("ROOT")){
// start Activity..