Android: Is there another way to display data from a string array? - android

I am trying to display the steps to a recipe, the recipe is stored in a string array.
Im trying to get each step to be inserted into a text view, and have the following code:
public class MethodActivity extends ListActivity{
ListView recipes;
Intent myIntent;
String value;
TextView editvalue;
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipemethod);
editvalue = (TextView)findViewById(R.id.method);
value = getIntent().getStringExtra("searchValue");
editvalue.setText(value);
final String[] words = getResources().getStringArray(R.array.Lasagna);
final TextView tw=(TextView)findViewById(R.id.method);
for(int item = 0;item<words.length;item++){
tw.setText(words [item]);
}
}
}
I am also wanting to make it dynamic so does anyone know how I can do that? (e.g. depending on what the user clicked that recipe is shown).
Thanks

It might be easier to actually use your ListActivity's ListView... You can even show your recipe in another ListView, as it will undoubtedly be more intuitive for the user...
A simple code that does this would go somewhat in the following lines:
File 1: RecipeListActivity.java (shows list of recipes)
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, RecipeActivity.class);
intent.putExtra(RecipeActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
File 2: RecipeActivity.java (shows a recipe in a list)
package com.epichorns.testproject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class RecipeActivity extends ListActivity {
final static public String EXTRA_RECIPEARRAY = "recipeArray";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] recipeArray = getIntent().getStringArrayExtra(EXTRA_RECIPEARRAY);
if(recipeArray!=null){
if(recipeArray.length>0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recipeArray);
setListAdapter(adapter);
}
}
}
}
Alternately, here is a code which composites a TextView below the recipes list in order to show the recipe content without opening another Activity:
File: RecipeListActivity.java
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
TextView mTextView_recipeTitle;
TextView mTextView_recipe;
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView_recipe = (TextView)findViewById(R.id.recipeText);
mTextView_recipeTitle = (TextView)findViewById(R.id.recipeTitle);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
mTextView_recipeTitle.setText(mRecipesArray[position].name);
mTextView_recipe.setText("");
String[] recipeSteps = mRecipesArray[position].steps;
for(int i=0;i<recipeSteps.length;i++){
mTextView_recipe.append(recipeSteps[i]+"\n");
}
}
}
File: 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" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#400000FF"
/>
<TextView
android:id="#+id/recipeTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#4000FF00"
/>
<TextView
android:id="#+id/recipeText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40FF0000"
/>
</LinearLayout>

You will want to use tw.append() instead of setText, otherwise all you will ever see is the last string in the array.
Make it dynamic, I would use a fragments (using the Android Support Library if on older android versions) model, load each array, attaching the string array as a bundle to the fragment before launching.
Fragment tut:http://developer.android.com/guide/topics/fundamentals/fragments.html
Support library: http://developer.android.com/training/basics/fragments/support-lib.html

Related

NumberFormatException invalid int

this is my saveddata.java page who can I solve
when I want to update data its say number expectation
and data insert but not update
I am trying to take the input values from EditText and I want to save it to SQLite Database. I don't know how to use the logcat [also please explain how can I read the errors from the LogCat].
package com.turningpoint.currencycounter;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class saveddata extends Activity{
DBHelper mydb;
private ListView obj;
ListViewAdapter lviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditem);
ListViewAdapter arrayAdapter;
mydb = new DBHelper(this);
List<String> friendsnames= mydb.getAllCotacts();
List<String> friendsnames2= mydb.getAllCotacts2();
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
String frnames2[]=friendsnames2.toArray(new String[friendsnames2.size()]);
arrayAdapter = new ListViewAdapter(this, frnames, frnames2);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2;
List array_list = mydb.getAllCotacts();
String s = array_list.get(id_To_Search).toString();
Cursor c2 = mydb.getData4(s);
while (c2.moveToNext()) {
String id = c2.getString(0);
String code = c2.getString(1);
// String code ..give me Number inut Expetation
int id2 = Integer.parseInt(id);
int code2 = Integer.parseInt(code);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id2);
int update=1;
dataBundle.putInt("update", update);
dataBundle.putInt("code", code2);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
Toast.makeText(getApplicationContext(), code, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show();
}
});
}
}
Use android:inputType="number" in EditText to make sure that the input is a number not a string or a charater like this
<EditText
.
.
.
android:inputType="number"
/>
Another solution:
Check if it is a number programmatically
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());
Read this article. You will know how to use the logcat
https://guides.codepath.com/android/Debugging-Exceptions-within-your-App
I solve this problem
int code2 = Integer.parseInt(code);
this c2.getString(1) could not Int its give me String

java.lang.NullPointerException: Attempt to invoke virtual method android studio [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i have problem with my android studio i want to passing data with parcel but it cant cause i get this message if i click my list view always get force close, how to fix it?
error
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MovieDetail extends AppCompatActivity {
String txt_name;
String txt_deskripsi;
int foto;
public static final String EXTRA_MOVIE = "text_extra_movie";
TextView tvName, txt_detail;
ImageView imgposter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
tvName = findViewById(R.id.text_ph);
txt_detail = findViewById(R.id.txt_deksrip);
imgposter = findViewById(R.id.img_poster);
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
txt_name = film.get(0).getNama();
tvName.setText(txt_name);
txt_deskripsi = film.get(0).getDeskripsi();
txt_detail.setText(txt_deskripsi);
foto = film.get(0).getFilm();
imgposter.setImageResource(foto);
}
}
movieDetail.java
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FilmAdapter adapter;
private String[] dataNama;
private String[] dataDeskrip;
private TypedArray dataPhoto;
private ArrayList<Film> filmed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new FilmAdapter(this);
ListView listView = findViewById(R.id.lv_list);
listView.setAdapter(adapter);
prepare();
addItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, MovieDetail.class);
ArrayList<Film> movies = new ArrayList<Film>();
Film movie = new Film();
movie.setFilm(dataPhoto.getResourceId(i, -1));
movie.setNama(dataNama[i]);
movie.setDeskripsi(dataDeskrip[i]);
movies.add(movie);
intent.putParcelableArrayListExtra(MovieDetail.EXTRA_MOVIE, movies);
startActivity(intent);
}
});
}
#Override
public void onClick(View v) {
}
private void addItem(){
ArrayList<Film> films = new ArrayList<>();
for (int i = 0; i < dataNama.length; i++){
Film film = new Film();
film.setFilm(dataPhoto.getResourceId(i, -1));
film.setNama(dataNama[i]);
film.setDeskripsi(dataDeskrip[i]);
films.add(film);
}
adapter.setFilms(films);
}
private void prepare(){
dataNama = getResources().getStringArray(R.array.data_film);
dataDeskrip = getResources().getStringArray(R.array.data_deskripsi);
dataPhoto = getResources().obtainTypedArray(R.array.data_foto);
}
}
mainactivity.java
You need to initialize the ArrayList<> first.
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
Then you can access it's value
txt_name = film.get(0).getName();
tvName.setText(txt_name);

Call another activity in Android using onPostExecute method list item click event in AsyncTask

I am working on a project which populating SQLite database table for list view and using simple array adapter.
I'm using Asyntask for that purpose and I have problem when:
I want to call another activity and
pass some values which I get from the setOnItemClickListener
I need to archive this two things in onPostExecute setOnItemClickListener method. This is my code for that.
package com.me.doctor.doctor_me;
import android.app.Activity;
import android.app.Application;
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.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Doctor,String> {
Context ctx;
DoctorAdapter doctorAdapter;
Activity activity;
ListView listView;
Doctor doctor;
DisplayDoctor displayDoctor;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity) ctx;
doctor = new Doctor();
displayDoctor = new DisplayDoctor();
}
#Override
protected String doInBackground(String... strings) {
String method = strings[0];
DatabaseOperation databaseOperation = new DatabaseOperation(ctx);
if(method.equals("get_info")){
listView = activity.findViewById(R.id.display_list_view);
SQLiteDatabase db = databaseOperation.getReadableDatabase();
Cursor cursor = databaseOperation.getInformation(db);
doctorAdapter = new DoctorAdapter(ctx,R.layout.display_doctor_row);
String name, category, hospital;
int id;
while(cursor.moveToNext()){
id = cursor.getInt(cursor.getColumnIndex("d_id"));
name = cursor.getString(cursor.getColumnIndex("d_name"));
category = cursor.getString(cursor.getColumnIndex("d_category"));
hospital = cursor.getString(cursor.getColumnIndex("d_hospital"));
Doctor doctor = new Doctor(id,name,category,hospital);
publishProgress(doctor);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Doctor... values) {
// add each of doctor class object add method inside the adapter class
doctorAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String s) {
if(s.equals("get_info")){
listView.setAdapter(doctorAdapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Doctor doctor = (Doctor)parent.getItemAtPosition(position);
String ID = Integer.toString(doctor.getId());
Toast.makeText(ctx,ID,Toast.LENGTH_LONG).show();
// I need fire another activity and pass some values which i getting here
}
});
}else{
Toast.makeText(ctx,s,Toast.LENGTH_LONG).show();
}
}
}
And this is the class which call to the AsyncTask Class
package com.me.doctor.doctor_me;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayDoctor extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_doctor_layout);
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute("get_info");
}
}
I had investigate closed question on Stack Overflow, but I did not found a solution.
Short answer:
you already have context in Background task
Context ctx;
use this this to call next activiry
ctx.startActivity(nextActivityIntent)
u can add values to the intent like this
Intent nextActivityIntent = new Intent(ctx,NextActivity.class);
nextActivityIntent.putExtra("data", "some data");
with async task i guess you are trying to query data base on another thread
You can use loaders for the same
Loaders run on separate thread
here is a simple example of cursor loader
example taken from github
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks {
public static final int LOADER_ID = 0;
private ArrayAdapter<String> forecastAdapter;
private ForecastAdapter mForecastAdapter;
public ForecastFragment() { }
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
getLoaderManager().initLoader(LOADER_ID, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//some database query
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//some action
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}

Refreshing ListView each time I search a new term

I am using google book API to search a book with the title.It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
There is a peculiar error. When I search a book it shows me 3 to 4 books whereas I have set MaxResult to 10. When I manually call the API in the browser I get 10 results.
Here is the code I am using.
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Book>>{
private static final int BOOK_ID = 1;
public static final String LOG_TAG = MainActivity.class.getName();
private static String book_url;
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.search);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchTerm=(EditText)findViewById(R.id.search_book);
String search=searchTerm.getText().toString();
book_url="https://www.googleapis.com/books/v1/volumes?q="+search+"&maxResults=10";
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_ID, null, MainActivity.this);
mAdapter=new BookAdapter(MainActivity.this,new ArrayList<Book>());
ListView bookListView=(ListView)findViewById(R.id.list);
mAdapter.notifyDataSetChanged();
bookListView.setAdapter(mAdapter);
}
});
}
public Loader<List<Book>> onCreateLoader(int i,Bundle bundle){
return new BookLoader(this,book_url);
}
public void onLoadFinished(Loader<List<Book>> loader,List<Book> books){
mAdapter.clear();
if(books!=null&&!books.isEmpty()){
mAdapter.addAll(books);
}
}
public void onLoaderReset(Loader<List<Book>> loader){
mAdapter.clear();
}
}
I tried notifyDataSetChanged(). But it doesn't work.
Here is the code for custom adapter
package com.example.android.booksearch;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by AKSPAN12 on 19-07-2017.
*/
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, List<Book> books) {
super(context, 0,books);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView=convertView;
if(listItemView==null){
listItemView= LayoutInflater.from(getContext()).inflate(R.layout.book_list,parent,false);
}
Book currentBook=getItem(position);
String author=currentBook.getAuthor();
TextView authorView=(TextView)listItemView.findViewById(R.id.book_author);
authorView.setText(author);
String bookName=currentBook.getBook();
TextView bookView=(TextView)listItemView.findViewById(R.id.book_name);
bookView.setText(bookName);
return listItemView;
}
}
It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
You probably need to restart your loader.

Filter custom ArrayAdapter or implement search in activity

I have successfully implemented listview from MYSQL database with the help of a tutorial using Adapter. Now I need to add a filter to the displayed listview or some kind of search dialog. I am really new to android. I want to search the database and display the result in the next activity. A detailed explanation will be so much appreciated. I know how to invoke the search dialog but i am notable to proceed ahead. Here is the activity which consist of the databse in listview:
DBLib.java
package com.example.test;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class DBLib extends ListActivity implements OnClickListener{
private ProgressDialog pDialog;
private Button b_search;
private EditText et;
private static final String READ_DB_URL ="http://crshaggy.byethost7.com/webservice/warehouse.php";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "id";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblib_list);
b_search=(Button)findViewById(R.id.listsearch);
b_search.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onSearchRequested();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_DB_URL);
try{
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.post, new String[] { TAG_TITLE, TAG_ID},
new int[] { R.id.title});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DBLib.this);
pDialog.setMessage("Loading Warehouse...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Layout of list
<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="#color/customgrey"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.test.DBLib" >
<Button
android:id="#+id/listsearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/searchbutton" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/listsearch" >
</ListView>
</RelativeLayout>
Edit 1
I have updated my code a bit I have added a onTextChanged() method but it is giving a null pointer exception. I have just changed the OnPostCreate() method which I am posting here:
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
inputSearch = (EditText) findViewById(R.id.et_search);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
DBLib.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
The SimpleAdapter already comes enabled with filtering capabilities. You'll just need to invoke something like:
getListAdapter().getFilter().filter("Text to search for");
That's it. Android will handle filtering through your data and displaying those that match the given string.
Update - Custom Filter
To customize how the filter searches is a lot more involved. The short answer, you'll need to write your own version of the SimpleAdapter. AFAIK, none of the Android provided adapters provide an easy solution for how to customize the filtering logic. It's why I am building up Advanced-Adapters, unfortunately I haven't written a solution for the SimpleAdapter yet. It's all ArrayAdapter and SparseArray alternatives right now.
You'll probably find lots of people and examples saying to extend the SimpleAdapter class and override the getFilter() method to have it return a new Filter class implemented by you. You can then use your mCommentList arraylist to figure out how to filter the data. While this will work in some situations, it's the incorrect approach and will fail for various cases.
The correct solution is to create your own adapter class that behaves like SimpleAdapter but extends the BaseAdapter class...which basically means create your own adapter from scratch. Being new to Android, it can be a very daunting task and there's a lot to learn and understand on how adapters work.
The easiest way to do this would be to literally copy the SimpleAdapter source code into your project and then manually change the filter code's logic to how you want it. The logic to adjust specifically occurs within this for loop. Keep in mind, that's within the performFiltering() method which is on a background thread! Hence all the synchronized blocks.

Categories

Resources