Search keyword with values in arraylist in android - android

I am new to android development. I have created a search widget in ActionBar. Now I have to search my keyword with value stored in ArrayList. How can I get value of that searched keyword in a variable? Please give me some sample code for that.

You have to set an OnQueryTextListener to your searchView. Like this:
//listener to when the user changes the text
_searchView.setOnQueryTextListener(new OnQueryTextListener() {
boolean _first = true;
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String str) {
//do you arraylist filtering here
ArrayList<String> arrayList = new ArrayList<String>(); //your arraylist, that you will filter
for(String arrayItem:arrayList){
if(arrayItem.contains(str)){
//add this item to your new list
}
}
return true;
}
});
Then you just have to refresh your listAdapter with the new filtered array.

Try below code snippet
actionbar_serch.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:background="#drawable/action_header"
android:gravity="center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/edit_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search"
android:paddingLeft="15dip"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textCursorDrawable="#null" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.demosearch;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
Button btn_search;
ArrayList<String> item_array;
EditText edit_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item_array=new ArrayList<String>();
for(int i=0;i<10;i++)
{
item_array.add("item"+i);
}
ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(R.layout.actionbar_serch);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
btn_search=(Button)findViewById(R.id.btn_search);
edit_search = (EditText) findViewById(R.id.edit_search);
edit_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String item=s.toString();
for(int i=0;i<item_array.size();i++)
{
if(item.equals(item_array.get(i)))
{
Log.e("Search item position is=", ""+i);
break;
}
}
}
});
}
}
Hope this helps you!!!!!
If it is not working please let me know i will try to help you more.

Related

How to make only the list title visible in the list menu and not the entire content of the list item in listview android studio?

I'm trying to make a simple note-taking app. I tried to display the notes in the listview. But when I add more content to the note it displays the entire content in the main menu of the list view. How to make only the title of the list visible in the Listview and the content visible only when we open the list item?
MainActitvity.java
package com.example.notes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes=new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()==R.id.add_note){
Intent intent=new Intent(getApplicationContext(),NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview=(ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set=(HashSet<String>)sharedPreferences.getStringSet("notes",null);
if(set==null) {
notes.add("Example note");
}
else{
notes=new ArrayList(set);
}
notes.add("Note 1");
arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,notes) ;
listview.setAdapter(arrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),NoteEditorActivity.class);
intent.putExtra("noteId",i);
startActivity(intent);
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
final int itemToDelete=i;
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("are you sure?")
.setMessage("do you want to delete?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set=new HashSet<>(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes",set).apply();
}
})
.setNegativeButton("no",null)
.show();
return true;
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/note1"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
note_editor_activity.java
package com.example.notes;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.HashSet;
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor);
EditText editText=(EditText) findViewById(R.id.editText);
Intent intent=getIntent();
noteId=intent.getIntExtra("noteId",-1);
if(noteId!=-1){
editText.setText(MainActivity.notes.get(noteId));
}
else{
MainActivity.notes.add("");
noteId=MainActivity.notes.size()-1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId,String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set=new HashSet<>(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes",set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
acitivity_node-editor.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/olo"
tools:context=".NoteEditorActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
android:padding="0dp"
tools:layout_editor_absoluteX="118dp"
tools:layout_editor_absoluteY="91dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
add_note_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/add_note" android:title="Add note"></item>
</menu>
Sorry, about the former one, I didn't explain properly using another format use two edittext one for title and one for the body.Save them in different preferences using the body key as the title
Pass the title preference to the listview.

How to change setText when i delete the data

I want to change my Button text when i delete the items
i already checked it getText, when i getText it shows that the data
already changed but when i try to setText, it's not show to me
In this case what shold i do?
This is my f_productAdapter
package com.example.together.Adapter;
import android.content.Context;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.example.together.Activities.EditProfileActivity.TAG;
public class f_productAdapter extends BaseAdapter {
Button b;
LayoutInflater inflater = null;
private ArrayList<FuneralProdcutOrder> list;
public f_productAdapter(ArrayList<FuneralProdcutOrder> f_order) {
super();
list = f_order;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return list.get(position).hashCode();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_funeralorder, parent, false);
}
TextView tv_name = convertView.findViewById(R.id.productnm); //상품이름
TextView tv_price = convertView.findViewById(R.id.productpri); //상품 가격
ImageView tv_img = convertView.findViewById(R.id.pro_img);
Button tv_delete = convertView.findViewById(R.id.deleteBtn);
FuneralProdcutOrder getProlist = list.get(position);
tv_name.setText(getProlist.getName());
tv_price.setText(getProlist.getPrice());
Picasso.get().load(getProlist.getImg()).fit().into(tv_img);
LayoutInflater inflaters = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Toplayout = inflaters.inflate(R.layout.activity_goodbyepet_reservation_result, null );
//
b = Toplayout.findViewById(R.id.f_orderBtn);
TextView test = Toplayout.findViewById(R.id.toolbar_title);
Log.e("test",test.getText()+"");
// Log.e("view context", parent.getContext()+"");
// Log.e("view position", position+"");
// Log.e("view count", list.size()+"");
// Log.e("view",b.getText()+"");
// b.setText("테스트");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("view alert" ,"확실히 버튼 객체를 찾았습니다 눌림");
}
});
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
return convertView;
}
}
This is my reservationResultActivity
package com.example.together.Activities.GoodbyePet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import com.example.together.Adapter.f_productAdapter;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class GoodbyepetReservationResultActivity extends AppCompatActivity {
// private TextView tvParent, tvChild;
Toolbar myToolbar;
ListView funeralview;
Button Btn;
private ArrayList<FuneralProdcutOrder> f_order = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goodbyepet_reservation_result);
int total_price = 0;
//리스트뷰선언
funeralview = findViewById(R.id.funeral_order);
//예약 버튼
Btn = findViewById(R.id.f_orderBtn);
//툴바 선언
myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//액션바 왼쪽에 버튼
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_btn_back);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for (int i = 0; i < MyCategoriesExpandableListAdapter.parentItems.size(); i++ ) {
for (int j = 0; j < MyCategoriesExpandableListAdapter.childItems.get(i).size(); j++ ){
String isChildChecked = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.IS_CHECKED);
if (isChildChecked.equalsIgnoreCase(ConstantManager.CHECK_BOX_CHECKED_TRUE)) {
// tvParent.setText(tvParent.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME));
// tvChild.setText(tvChild.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE));
String name = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME);
String price = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE);
String img = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_IMAGE);
f_order.add(new FuneralProdcutOrder(name,price,img));
total_price = total_price + Integer.parseInt(price);
}
}
}
f_productAdapter orAdapter = new f_productAdapter(f_order);
// orAdapter.setHasStableId(true);
Log.e("view activiey", f_order.size()+"안녕");
funeralview.setAdapter(orAdapter);
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//액션바 등록
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alldelete_manu, menu) ;
return true ;
}
//액션바 클릭 이벤트
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ((TextView)findViewById(R.id.textView)).setText("SEARCH") ;
return true;
case R.id.settings:
// ((TextView)findViewById(R.id.textView)).setText("ACCOUNT") ;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
What i want to do
when i delete the button directly change buttons text also change
but setText() is not working
how to change that?
Click delete button
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
What i want to change the button text
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
This is my XML That include button what i want to change the text
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".Activities.GoodbyePet.GoodbyepetReservationResultActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/mdtp_white"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예약 상세서"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
/>
</android.support.v7.widget.Toolbar>
<ListView
android:id="#+id/funeral_order"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:drawSelectorOnTop="false">
</ListView>
<Button
android:id="#+id/f_orderBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:layout_margin="10dp"
android:text="바뀌어주세요"
android:background="#drawable/button_radius"
android:textSize="18dp"/>
</LinearLayout>
Create an interface class like this;
You can set many kind of information as a parameter about your deleted item and send it to your activity.
public interface ItemSelectedListener{
void onItemSelected(boolean isDeleted);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListener listener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (ItemSelectedListener listener : mItemSelectedSubscribers ) {
listener.onItemSelected(true);
}
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
boolean isDeleted;
#Override
public void onItemSelected(boolean isDeleted) {
this.isDeleted = isDeleted;
}
You know now item is deleted or not. When a button deleted you can change text by using your method.
if(isDeleted){
btn.setText(changeText)
}
Hope this help!

How to fetch data from a custom list view with multiple radio buttons

I have gone through a lot of links here, but yet i was not able to get my stuff working. Can you please help me fetch data from my custom list.
Details are as under :- My custom list 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:orientation="vertical" >
<RadioGroup
android:id="#+id/radioGroup_option"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
<RadioButton
android:id="#+id/rb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="#+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
I am populating a List through the UI the code for that is :-
package com.example.customadapter;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CustomAdapter extends ActionBarActivity {
AddDataToArray mydata;
EditText qstno,qstn,opt1,opt2;
Button btn_save,btn_display;
int questio_no;
String question,option1,option2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_adapter);
mydata=AddDataToArray.getInstance();
qstno=(EditText)findViewById(R.id.edt_qstn_no);
qstn=(EditText)findViewById(R.id.edt_add_qstn);
opt1=(EditText)findViewById(R.id.edt_opt1);
opt2=(EditText)findViewById(R.id.edt_opt2);
btn_save=(Button)findViewById(R.id.btn_save);
btn_display=(Button)findViewById(R.id.btn_display);
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
questio_no=Integer.parseInt(qstno.getText().toString());
question=qstn.getText().toString();
option1=opt1.getText().toString();
option2=opt2.getText().toString();
System.out.println("Questio added in the UI --> "+ question);
String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
qstn.setText("");
opt1.setText("");
opt2.setText("");
}
});
btn_display.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i=0;i<mydata.myQstnList.size();i++)
{
System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
//System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
}
Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_adapter, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Finally i made an adapter from base adapter as follows:-
package com.example.customadapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Question> mQuestion;
Context context;
public MyAdapter(Context context,List<Question> mQuestion) {
super();
this.context=context;
this.mQuestion = mQuestion;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mQuestion.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mQuestion.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) {
// TODO Auto-generated method stub
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.customized_view, parent,false);
holder = new ViewHolder();
holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
view.setTag(mQuestion);
}else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
Question qstnRef=mQuestion.get(position);
holder.tv_qstn.setText(qstnRef.getQstn());
holder.rb_opt1.setText(qstnRef.getOpt1());
holder.rb_opt2.setText(qstnRef.getOpt2());
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//List<Question> data =(List<Question>) group.getTag();
//Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
RadioButton r_btn=(RadioButton)group.getChildAt(i);
if (r_btn.getId() == checkedId){
System.out.println(r_btn.getText().toString());
}
}
}
});
return view;
}
private class ViewHolder {
public TextView tv_qstn;
public RadioButton rb_opt1,rb_opt2;
public RadioGroup rg;
}
}
But i am trying to get this data that i enter in the UI, but I am not able to get this to work, please provide me assistance !!!!
The code in the current format is giving me runtime error :-
05-09 06:01:06.669: E/AndroidRuntime(2420):
java.lang.ClassCastException: android.widget.TextView cannot be cast
to android.widget.RadioButton
05-09 06:01:06.669: E/AndroidRuntime(2420): at
com.example.customadapter.MyAdapter$1.onCheckedChanged(MyAdapter.java:83)
group.getChildCount() returns 3 as it has 3 child. but 1 child is of TextView that's why you were getting java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
To avoid it do type checking using instanceof before typecasting.
do like this:
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
RadioButton r_btn = (RadioButton) group.getChildAt(i);
if (r_btn.getId() == checkedId) {
System.out.println(r_btn.getText().toString());
}
}
}

Unfortunately App has stopped - error in Spinner

I have tried everything but still am not able to figure out what is wrong in this code, whenever I click on the Button 'Get Fare' , a dialog opens showing "Unfortunately app has stopped". Please help ...
Code for MetroFare.java
package com.myapp.anuj;
import com.myapp.anuj.MetroFare;
import com.myapp.anuj.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MetroFare extends Activity implements OnClickListener, OnItemSelectedListener{
String start[] = {"Shastri Nagar", "Kashmere Gate", "Dwarka Mor"};
String dest[] = {"Pratap Nagar", "Rajiv Chowk", "Kirti Nagar"};
Spinner starting, destination;
Button getfare;
int fare = 0;
int s=0, d=0;
TextView result;
int farearray[][] = {{8,15,14}, {10,12,15}, {21,18,15}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.kuchbhi);
getfare = (Button) findViewById(R.id.bGetFare);
result = (TextView) findViewById(R.id.tvShowFare);
getfare.setOnClickListener(this);
ArrayAdapter<String> adapterStart = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, start);
ArrayAdapter<String> adapterDest = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, dest);
starting = (Spinner) findViewById(R.id.spinnerStart);
destination = (Spinner) findViewById(R.id.spinnerDest);
starting.setAdapter(adapterStart);
destination.setAdapter(adapterDest);
starting.setOnItemSelectedListener(this);
destination.setOnItemSelectedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sfare = getString(fare);
result.setText(sfare);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
s = starting.getSelectedItemPosition();
d = destination.getSelectedItemPosition();
fare = farearray[s][d];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Code for kuchbhi.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" >
<Spinner
android:id="#+id/spinnerStart"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinnerDest"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bGetFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Fare" />
<TextView
android:id="#+id/tvShowFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
As I mentioned, your problem is this call: getString(fare), which is attempting to retrieve a String resource with an id the value of fare. Judging from your code, I'm assuming that you're simply trying to display the String value of fare in a TextView, in which case change that call as follows:
String sfare = String.valueOf(fare);

Using few ListView's in one activity and layout

I'm trying to organize data recieved by SMS messages in specified ListView's.
I tried to create and activity which will contain 3 ListView's in one layout.
But, while running the activity it crashes.
Can someone help with this?
Here is the XML code:
<?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" >
<ListView
android:id="#+id/idList"
android:layout_width="112dp"
android:layout_height="384dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/namesList"
android:layout_width="96dp"
android:layout_height="387dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/phonesList"
android:layout_width="wrap_content"
android:layout_height="382dp"
android:layout_gravity="center" >
</ListView>
</LinearLayout>
And here is the activity code:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DataLists extends ListActivity implements OnClickListener {
ListView idList, namesList, phonesList;
MyReciever mr;
ArrayList<String>ids= new ArrayList<String>();
ArrayList<String>names=new ArrayList<String>();
ArrayList<String>phones=new ArrayList<String>();
ArrayAdapter<String> idAdapter, namesAdapter, phonesAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details_lists);
idList=(ListView)findViewById(R.id.idList);
namesList=(ListView)findViewById(R.id.namesList);
phonesList=(ListView)findViewById(R.id.phonesList);
idAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,ids );
idList.setAdapter(idAdapter);
namesAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
namesList.setAdapter(namesAdapter);
phonesAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, phones);
phonesList.setAdapter(phonesAdapter);
}
public void addItemToIdList(String st)
{
ids.add(st);
idAdapter.notifyDataSetChanged();
}
public void addItemToNamesList(String st)
{
names.add(st);
namesAdapter.notifyDataSetChanged();
}
public void addItemToPhonesList(String st)
{
phones.add(st);
phonesAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle=intent.getExtras();
SmsMessage[]msgs=null;
if(bundle!=null)
{
Object[]pdus=(Object[]) bundle.get("pdus");
msgs=new SmsMessage[pdus.length];
for(int i=0;i<msgs.length;i++)
{
int index=0, prev=0;
String msgBody=msgs[i].getMessageBody().toString();
index=msgBody.indexOf(';');
prev=index;
String name=msgBody.substring(0, index);
addItemToNamesList(name);
msgBody=msgBody.substring(index+1);
index=msgBody.indexOf(';');
String id=msgBody.substring(prev, index);
addItemToIdList(id);
msgBody=msgBody.substring(index+1);
String phone=msgBody;
addItemToPhonesList(phone);
}
}
}
}
}
You have extended ListActivity. This is a convenience class that can be used to display a single ListView. The crash is clearly described in your logcat/stacktrace:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Since your layout contains 3 ListViews, you probably can't use ListActivity anyway. Just change your activity to extend Activity and go from there.

Categories

Resources