Progress dialog issue in Android app - java

I'm having trouble with the way I am trying to get the progress dialogue to work.
First I initialise the progress dialogue in my searchable activity class as so:
ProgressDialog pd;
Then I show the progress dialogue when a search is executed in my dosearch method:
public void doSearch(String query) {
pd = ProgressDialog.show(SearchableActivity.this, "Last Fm", "Searching Tracks...");
String[] result = new String[] {"searching..."};
AlbumSearchService service = new AlbumSearchService(query);
service.addListener(this);
thread = new Thread(service);
thread.start();
setListAdapter(new ArrayAdapter<String> (this ,
R.layout.album_list_cell,
R.id.text,
result));
Log.v("blah", "doSearch was called");
service.run();
}
And finally, once the search is complete, I dismiss the progress indicator in my service complete method.
pd.dismiss();
I fail to see what I'm doing wrong, whenever I commence a search, the progress dialogue feature does not appear please help :(
Thank you!
Edit:
Here's my full code for those with a sharp eye. I think it may be a thread issue but i have no clue.
public class SearchableActivity extends ListActivity implements ServiceListener {
private Thread thread;
private ArrayList searchResults;
ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchResults = new ArrayList<JSONObject>(); // initialise array list to
// hold the results so
// we can do something
// with them
// this gets the intent being sent over
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
}
#Override
// this method handles what happens when a user clicks a result.
// the search item is broadcasted for other people to use.
protected void onListItemClick(ListView l, View v, int position, long id) {
if (position < searchResults.size()) { // if the position is less than
// the size of the results array
// then...
Intent result = new Intent(); // create a new intent called result.
result.setAction(SEARCH_BROADCAST); // place the broadcast message
// on the intent.
result.putExtra("result", searchResults.get(position).toString()); // add
// extended
// data
// to
// the
// intent
this.sendBroadcast(result);
this.finish();
}
}
public void doSearch(String query) {
pd = ProgressDialog.show(SearchableActivity.this, "Last Fm",
"Searching Tracks...");
String[] result = new String[] { "searching..." };
AlbumSearchService service = new AlbumSearchService(query);
service.addListener(this);
thread = new Thread(service);
thread.start();
setListAdapter(new ArrayAdapter<String>(this, R.layout.album_list_cell,
R.id.text, result));
Log.v("blah", "doSearch was called");
service.run();
}
public void ServiceComplete(AbstractService service) {
if (pd.isShowing()) {
pd.dismiss();
}
if (!service.hasError()) {
AlbumSearchService albumService = (AlbumSearchService) service;
String[] result = new String[albumService.getResults().length()];
searchResults.clear();
for (int i = 0; i < albumService.getResults().length(); i++) {
try {
searchResults.add(albumService.getResults()
.getJSONObject(i)); // gets the json object for each
// result and adds to array
result[i] = albumService.getResults().getJSONObject(i)
.getString("name");
} catch (JSONException ex) {
result[i] = "Error";
}
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.album_list_cell, R.id.text, result));
} else {
String[] result = new String[] { "No Results" };
setListAdapter(new ArrayAdapter<String>(this,
R.layout.album_list_cell, R.id.text, result));
}
}
public static final String SEARCH_BROADCAST = "search_result_selected";
}

Related

How to automatically refresh a Listview? [duplicate]

This question already has answers here:
android auto-refresh listview items
(2 answers)
Closed 4 years ago.
I have an android listview, but I have to relance the application every time that I want to refresh the list. I have two questions, please:
1) How to refresh it automatically?
2) How to do to receive a notification when an item is added to the database?
So it just tests if an item is added, I receive a notification, when I Click on it I will be able to see the list of items.
This is my code:
public class MainActivity extends Activity {
ListView SubjectFullFormListView;
ProgressBar progressBar;
String HttpURL = "http://254.221.325.11/test/Subject.php";
ListAdapter adapter ;
List<Subject> SubjectFullFormList;
EditText editText ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);
editText = (EditText)findViewById(R.id.edittext1);
progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(this).execute();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subject subject;
SubjectFullFormList = new ArrayList<Subject>();
for (int i = 0; i < jsonArray.length(); i++) {
subject = new Subject();
jsonObject = jsonArray.getJSONObject(i);
subject.Subject_Name = jsonObject.getString("SubjectName");
subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");
SubjectFullFormList.add(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
SubjectFullFormListView.setVisibility(View.VISIBLE);
adapter = new ListAdapter(SubjectFullFormList, context);
SubjectFullFormListView.setAdapter(adapter);
}
}
}
I find a solution but I don't know how and where to insert it:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
Thank you.
-> Write a runnable thread which calls the API of the list regularly after some time and on its response change the list in the adapter and call notifydatasetchanged().
-> By using FCM you can get the solution to question 2. When an item is added in DB generate a notification from server side and send it to clients sides and by using pending intent you can show the list when user tap on the notification.
(OR)
-> You can use the real-time DB Like Firebase DB or Realm etc. for this approach. This DB notify you when an item added to the list and you don't need threads to refresh list.

Android Error: IllegalStateException

I am working on a Bitcoin dashboard for Android. The following fragment uses the entered wallet address to display the balance in BTC. When an address is entered, it will add to the listview. When an item in the listview is selected, it will set the edittext to that address.
It is not yet complete, but for now it is throwing an error with the message, "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."
I currently have two example addresses in place for testing. If I select one then the other then the first again etc. it works fine. The error appears when I select one, press the button, then select the other.
public class WalletFragment extends Fragment {
ArrayList<String> savedWallets;
ArrayAdapter<String> listAdapter;
String newWalletAddress, jsonString, address, balance;
JSONObject jsonObj, data;
Double balanceDouble;
DecimalFormat df = new DecimalFormat("#.####");
private WalletListener listener;
public interface WalletListener {
void onCreateWallet(String newWalletAddress);
}
public WalletFragment() {
// Required empty public constructor
}
public static WalletFragment newInstance(ArrayList<String> wallets) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
fragment.setArguments(args);
return fragment;
}
public static WalletFragment newInstance(ArrayList<String> wallets, String json) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
args.putString("jsonString", json);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof WalletListener) {
listener = (WalletListener) context;
}
else {
throw new ClassCastException(context.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wallet, container, false);
ListView lv = (ListView) v.findViewById(R.id.walletListView);
df.setRoundingMode(RoundingMode.CEILING);
final EditText walletAddressEditText = (EditText) v.findViewById(R.id.walletAddressEditText);
TextView addressTV = (TextView) v.findViewById(R.id.walletAddresstextView);
TextView balanceTV = (TextView) v.findViewById(R.id.walletBalanceTextView);
savedWallets = getArguments().getStringArrayList("savedWallets");
if (savedWallets == null) {
savedWallets = new ArrayList<>();
}
savedWallets.add("198aMn6ZYAczwrE5NvNTUMyJ5qkfy4g3Hi");
savedWallets.add("1L8meqhMTRpxasdGt8DHSJfscxgHHzvPgk");
// TODO remove test addresses
jsonString = getArguments().getString("jsonString");
if (jsonString != null) {
try {
jsonString = getArguments().getString("jsonString");
jsonObj = new JSONObject(jsonString);
data = new JSONObject(jsonObj.getString("data"));
balance = data.getString("balance");
balanceDouble = Double.parseDouble(balance);
address = data.getString("address");
String walletAddressText = getResources().getString(R.string.wallet_address, address);
addressTV.setText(walletAddressText);
String walletBalanceText = getResources().getString(R.string.wallet_balance, df.format(balanceDouble));
balanceTV.setText(walletBalanceText);
// TODO add viewing for other wallet data at some point
} catch (Exception e) {
Log.d("TickerException", e.toString());
}
}
listAdapter = new ArrayAdapter<>(getActivity(), R.layout.main_list_rows, savedWallets);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String address = savedWallets.get(position);
Log.d("wallet", "Selected: " + address);
walletAddressEditText.setText(address);
}
});
Button button = (Button) v.findViewById(R.id.createWalletButton);
View.OnClickListener ocl = new View.OnClickListener() {
#Override
public void onClick(View view) {
newWalletAddress = walletAddressEditText.getText().toString();
if (walletAddressEntryStructuralValidation(newWalletAddress)) {
if (newWalletAddress != null) {
listener.onCreateWallet(newWalletAddress);
}
else {
Toast.makeText(getActivity(), "newWalletAddress is null", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getActivity(), "Please enter a valid wallet address (length is currently " + newWalletAddress.length() + ").", Toast.LENGTH_SHORT).show();
}
}
};
// TODO check if wallet is already on list
button.setOnClickListener(ocl);
return v;
}
public boolean walletAddressEntryStructuralValidation(String address) {
return ((address.length() > 25) &&
(address.length() < 36) && (
(address.substring(0,1).equals("1") ||
(address.substring(0,1).equals("3")))));
}
// Wallet addresses are 26-35 alphanumeric characters and begin with 1 or 3
}
I believe this is all the relevant code but I will be closely watching this thread if anyone needs to request additional source.
That message means that the contents of the adapter (the order of items you see in getItem) changed but notifyDataSetChanged or similar function wasn't called. When changing the items in your adapter contents (which in this case is the savedWallets array list) you must call one of those functions.
Note: If you're adding several objects at once, you only need to call it once after all are added/removed. If you're mutating an object but not adding/removing it, you do not need to call it, but calling it may be the easiest way of doing a redraw.

search filter for Listview [duplicate]

I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}

Android - Make a single activity in listview item

Can i call a single activity in listview, i have searching any code but i never understand how to implement it because i use JSON parsing in my code. can someone tell me how to do it with my code.
Here my MainActivity.java
public class MainActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS;
private static String url_daftar_rs = "http://192.168.43.226/jualan/barang_tes/list.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "nama_rs";
public static final String TAG_LINK_IMAGE_RS = "link_image_rs";
public static final String TAG_ALAMAT_RS = "alamat_rs";
public static final String TAG_TELEPON_RS = "telepon_rs";
public static final String TAG_HARGA_RS = "harga_rs";
Button ButttonInputRumahSakit;
// daftar_rs JSONArray
JSONArray daftar_rs = null;
ListView list;
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_load_barang);
// Hashmap for ListView
DaftarRS = new ArrayList<HashMap<String, String>>();
// Loading in Background Thread
new LoadDaftarRumahSakitActivity().execute();
// Get listview
list = (ListView) findViewById(R.id.list);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = DaftarRS.get(position);
Intent in = new Intent(MainActivity.this, SingleMenuItemActivity.class);
in.putExtra(TAG_ID_RS, map.get(TAG_ID_RS));
in.putExtra(TAG_NAMA_RS, map.get(TAG_NAMA_RS));
in.putExtra(TAG_LINK_IMAGE_RS, map.get(TAG_LINK_IMAGE_RS));
in.putExtra(TAG_ALAMAT_RS, map.get(TAG_ALAMAT_RS));
in.putExtra(TAG_TELEPON_RS, map.get(TAG_TELEPON_RS));
in.putExtra(TAG_HARGA_RS, map.get(TAG_HARGA_RS));
startActivity(in);
}
});
}
/**
*Updating parsed JSON data into ListView
**/
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new ListAdapter(this, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
//if result code 100 is received
//means user edited/deleted record
//reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
*Background Async Task to Load all record data by making HTTP Request
**/
class LoadDaftarRumahSakitActivity extends AsyncTask<String, String, String> {
/**
*Before starting background thread Show Progress Dialog
**/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Mohon tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
*getting All record data from url
**/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "GET", params);
// Check your log cat for JSON reponse
Log.d("Daftar Rumah Sakit: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Ada record Data (SUCCESS = 1)
//Getting Array of daftar_rs
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
// looping through All daftar_rs
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
//Storing each json item in variable
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c.getString(TAG_LINK_IMAGE_RS);
String alamat_rs = c.getString(TAG_ALAMAT_RS);
String telepon_rs = c.getString(TAG_TELEPON_RS);
String harga_rs = c.getString(TAG_HARGA_RS);
//creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to HashMap key => value
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_ALAMAT_RS, alamat_rs);
map.put(TAG_TELEPON_RS, telepon_rs);
map.put(TAG_HARGA_RS, harga_rs);
//adding HashList to ArrayList
DaftarRS.add(map);
}
} else {
//Tidak Ada Record Data (SUCCESS = 0)
//Akan menutup aplikasi
finish();
}
} catch (JSONException e) { e.printStackTrace();
}
return null;
}
/**
*After completing background task Dismiss the progress dialog
***/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all record rumah sakit
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// updating listview
SetListViewAdapter(DaftarRS);
}
});
}
}
}
Here my SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list);
Intent i = getIntent();
//now your item data are in i
String TAG_ID_RS = i.getStringExtra("TAG_ID_RS");
String TAG_NAMA_RS = i.getStringExtra("TAG_NAMA_RS");
String TAG_LINK_IMAGE_RS = i.getStringExtra("TAG_LINK_IMAGE_RS");
String TAG_ALAMAT_RS = i.getStringExtra("TAG_ALAMAT_RS");
String TAG_TELEPON_RS = i.getStringExtra("TAG_TELEPON_RS");
String TAG_HARGA_RS = i.getStringExtra("TAG_HARGA_RS");
TextView namaView = (TextView) findViewById(R.id.nama_rs);
ImageView link_img = (ImageView) findViewById(R.id.image_rs);
TextView alamat = (TextView) findViewById(R.id.alamat_rs);
TextView telepon = (TextView) findViewById(R.id.telepon_rs);
TextView harga = (TextView) findViewById(R.id.harga_rs);
namaView.setText(TAG_NAMA_RS);
//link_img.setImageBitmap(TAG_LINK_IMAGE_RS);
alamat.setText(TAG_ALAMAT_RS);
telepon.setText(TAG_TELEPON_RS);
harga.setText(TAG_HARGA_RS);
}
}
In your main activity's onCreate method, after your last line add:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
HashMap<String,String> item = (HashMap<String,String>) adapter.getItem(position);
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra("TAG_ID_RS", item.get("TAG_ID_RS"));
intent.putExtra("TAG_NAMA_RS", item.get("TAG_NAMA_RS"));
......
startActivity(intent);
}
});
In the YourSecondActivity.java there goes something like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoursecondactivity);
Intent i = getIntent();
//now your item data are in i
String TAG_ID_RS = i.getString("TAG_ID_RS");
String TAG_NAMA_RS = i.getString("TAG_NAMA_RS");
....
TextView namaView = (TextView)findViewById(R.id.yourNameView);
namaView.setText(TAG_NAMA_RS);
....
}
For your intent receiving activity you need to define an intent filter in the manifest file:
<activity android:name="SingleMenuItemActivity">
<intent-filter>
<action android:name="yourpackage.intent.action.showsinglemenuitem"/>
</intent-filter>
</activity>
Use the "yourpackage.intent.action.showsinglemenuitem" action name when constructing the INTENT to be p
I think I found out your problem finally:
In your MainActivity you define your field names as for example:
public static final String TAG_NAMA_RS = "nama_rs";
and you fill them with that name into the Intent,
but in your SingleMenuItemActivity you are trying to access them with different name:
String TAG_NAMA_RS = i.getStringExtra("TAG_NAMA_RS");
you need to do
String TAG_NAMA_RS = i.getStringExtra("nama_rs");

How to clear all items in a ListView while using List Adapter onTextChange?

I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back

Categories

Resources