I am developing one application in that I can shows route between source and destination And display some description about that route. Now I am trying to download that description in to my mobile. I am searched so such but I did not find any related example. please share any example for this
myCode
private class GetRouteTask extends AsyncTask<String, Void, String>{
private ProgressDialog pDialog;
String response="";
private WeakReference<ShowRoutesInMap> weakRef;
//public ArrayList<String> alter;
public ArrayList<String> route1;
public ArrayList<String> route2;
public ArrayList<String> route3;
PolylineOptions rectLine = null;
PolylineOptions rectLine1 = null;
PolylineOptions rectLine2 = null;
PolylineOptions rectLine3 = null;
public ArrayList<LatLng> directionPoint;
private ArrayList<String> alter;
public GetRouteTask(ShowRoutesInMap context){
this.weakRef =new WeakReference<ShowRoutesInMap>(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(ShowRoutesInMap.this);
if(!isFinishing()){
pDialog.setMessage("Please wait For TrafficJam Route...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if(sourcePosition!=null && destinationPostion!=null){
document = v2GetRouteDirection.getDocument(sourcePosition, destinationPostion,GMapV2Direction.MODE_DRIVING);
}
}
catch(Exception e){
return "exception caught";
}
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// if(!isFinishing()){
pDialog.dismiss();
// }
route1 = new ArrayList<String>();
route2 = new ArrayList<String>();
route3 = new ArrayList<String>();
if(result.equalsIgnoreCase("exception caught")){
Toast.makeText(getApplicationContext(), "INVALID VALUES", Toast.LENGTH_LONG).show();
}
else{
if (weakRef.get() != null && ! weakRef.get().isFinishing()){
// if(response.equalsIgnoreCase("Success")){
alter = v2GetRouteDirection.getAlternativeRoutes(document);
int duration = v2GetRouteDirection.getDurationValue(document);
Log.e("TRAFFIC DURATIONTIME",""+duration);
int trfficClearTime = v2GetRouteDirection.getDistanceValue(document);
Log.e("TRAFFIC TIME", ""+trfficClearTime);
for( j=0;j<alter.size();j++){
directionPoint =v2GetRouteDirection.getDirection(document, j);
ArrayList<String> desc = v2GetRouteDirection.getDescription(document,j);
if(j==0){
for(int l=0;l<desc.size();l++){
route1.add(desc.get(l));
Log.e("ROUTE1", desc.get(l).replace("\\<.*?>",""));
}
}
else if(j==1){
for(int l=0;l<desc.size();l++){
route2.add(desc.get(l));
Log.e("ROTE2", desc.get(l).replace("\\<.*?>",""));
}
}
else if(j==2){
for(int l=0;l<desc.size();l++){
route3.add(desc.get(l));
Log.e("ROTE2", desc.get(l).replace("\\<.*?>",""));
}
}
rectLine = new PolylineOptions().width(5).color(Color.RED).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
googleMap.addPolyline(rectLine);
getMarkersOnMap(googleMap);
alterRoutes1.setText("");
if(alter.size()==1){
alterRoutes1.setText(alter.get(0));
}
else if(alter.size()>=1 && alter.size()<=2){
alterRoutes1.setText(alter.get(0));
alterRoutes2.setText(alter.get(1));
}
else if(alter.size()>=1 && alter.size()<=3){
alterRoutes1.setText(alter.get(0));
alterRoutes2.setText(alter.get(1));
alterRoutes3.setText(alter.get(2));
}
}
}
alterRoutes1.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint1;
#Override
public void onClick(View v) { // TODO Auto-generated method stub
googleMap.clear();
// ArrayList<String> alter = v2GetRouteDirection.getAlternativeRoutes(document);
rectLine1 = new PolylineOptions().width(5).color(Color.GREEN).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint1 =v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint1.size(); i++) {
if(k==0){
rectLine1.add(directionPoint1.get(i));
}
}
googleMap.addPolyline(rectLine1);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route1.size();i++){
showDirection.append(route1.get(i).replaceAll("\\<.*?>",""));
}
}
});
alterRoutes2.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint2;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
googleMap.clear();
showDirection.setText("");
rectLine2 = new PolylineOptions().width(5).color(Color.MAGENTA).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint2 =v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint2.size(); i++) {
if(k==1){
rectLine2.add(directionPoint2.get(i));
}
}
googleMap.addPolyline(rectLine2);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route2.size();i++){
showDirection.append(route2.get(i).replaceAll("\\<.*?>",""));
}
}
});
alterRoutes3.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint3;
int count=0;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
googleMap.clear();
showDirection.setText("");
rectLine3 = new
PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint3
=v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint3.size(); i++) {
if(k==2){
rectLine3.add(directionPoint3.get(i));
}
}
googleMap.addPolyline(rectLine3);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route3.size();i++){
showDirection.append(""+ ++count);
showDirection.append(route3.get(i).replaceAll("\\<.*?
>",""));
}
}
});
}
}
}
public void getMarkersOnMap(GoogleMap gmap){
Markeropition1.position(sourcePosition).icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true);
Markeropition2.position(destinationPostion).icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true);
Markeropition1.draggable(true);
Markeropition2.draggable(true);
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(sourcePosition,10));
gmap.addMarker(Markeropition1);
gmap.addMarker(Markeropition2);
}
It is possible to generate pdf document in android from Api level 19. You can take reference from this link http://developer.android.com/reference/android/graphics/pdf/package-summary.html
Related
I have custom alert dailog with list and check i am trying to store selected checkbox in pref,how to store selected item in shared preference,i am able to select values from list?can any one help me with this?
class LoadAlldata extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
ArrayAdapter<String> adapterallstates;
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TestCountry.this);
pDialog.setMessage("Please..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(STATE_ID, c.getString(STATE_ID));
map.put(STATE_NAME, c.getString(STATE_NAME));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
final String[] arrallstates = new String[statedata.size()];
checked_state=new boolean[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(STATE_NAME);
}
txtvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(TestCountry.this)
.setTitle("Choose a Days")
.setMultiChoiceItems(arrallstates, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
//storing the checked state of the items in an array
checked_state[which] = isChecked;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String display_checked_days = "";
for (int i = 0; i < arrallstates.length; i++) {
if (checked_state[i] == true) {
display_checked_days = display_checked_days + " " + arrallstates[i];
}
}
Toast.makeText(TestCountry.this, "The selected is" + display_checked_days, Toast.LENGTH_SHORT).show();
//clears the array used to store checked state
for (int i = 0; i < checked_state.length; i++) {
if (checked_state[i] == true) {
checked_state[i] = false;
}
}
//used to dismiss the dialog upon user selection.
dialog.dismiss();
}
}).create().show();;
}
});
}
}
First write a method to setSelection mannually in Adapter.
private int selectedItem = -1;
public void setSelectedItem(int position) {
selectedItem = position;
notifyDataSetChanged();
} // Here selectedItem is global variable
In onBindViewHolder add this code :
if (position == selectedItem){
viewHolder.chkSelected.setChecked(stList.get(position));
viewHolder.chkSelected.setTag(stList.get(position));
} else {
viewHolder.chkSelected.setChecked(stList.get(position).isselected());
viewHolder.chkSelected.setTag(stList.get(position));
}
From your Activity you have to call setSelectedItem(position) from your adapter insance. For getting position you have already know the chekbox Id so you can get position of that Id from List.
To get position from List:
private int getSelectedItem(List<String> stList, String name) {
int pos = -1;
for(int i=0; i<stList.size(); i++) {
if(name.equals(stList.get(i)){
pos = i;
break;
}
}
return pos;
}
Try like this:
First make model class with getter setter:
private boolean checked;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
And in Adapter Class in getview write Code like this.
FilterModelClass model=stList.get(position);
viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(model));
Make class like below to handle checkedChangedListener
/*******************
* Checkbox Checked Change Listener
********************/
private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
private final FilterModelClass model;
private CheckUpdateListener(FilterModelClass model) {
this.model = model;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("onCheckedChanged", "isChecked: " + isChecked);
model.setChecked(isChecked);
notifyDataSetChanged();
}
}
I am working on an application that requires data to be displayed on a listview. The data to be displayed on the listview needs to be updated frequently so i created a sync-adapter which will be triggered my a broadcast message from gcm. When this occurs my AsyncTask loader.onContentChanged is called which call the loadinbackground method and all this works properly. The issues i am having is displaying the new data on the listview without restarting the activity. i am trying to get it to work like facebook news feed listview.
Please help me
My codes are as follows
SyncAdapter
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
Log.d(TAG, "onPerformSync for account[" + account.name + "]");
String theValue = mAccountManager.getUserData(account, "User_ID");
mContentResolver = mContext.getContentResolver();
final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
mLoader.onContentChanged();
}
Loader
public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
private static String url = "********************";
int success;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
Context mContext;
//private final Handler observerHandler;
public RoomListLoader(Context context,String nuser_id) {
super(context);
// TODO Auto-generated constructor stub
//mRoomList = nRoomList;
this.user_id = nuser_id;
this.mContext = context;
//observerHandler = new Handler();
}
#Override
public List<RoomList> loadInBackground() {
// TODO Auto-generated method stub
mRoomList.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id));
json = jsonParser.makeHttpRequest(url, "POST", params);
// final Context context = getContext();
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
rooms = json.getJSONArray(TAG_ROOMS);
// counter = json.getInt("counter");
counterOnGetRooms = json.getInt("count");
Log.d("counterOnGetRooms", "" + counterOnGetRooms);
// Log.v("counter", "" + counter);
for (int i = 0; i < rooms.length(); i++) {
tryme2++;
JSONObject c = rooms.getJSONObject(i);
// get room titles
roomTitle = c.getString("room_title");
retrievedRoomId = c.getString("room_id");
created_at = c.getString("created_at");
username = c.getString("username");
numOfComments = c.getString("counters");
filePath = c.getString("filePath");
Log.i("filePath", filePath);
details = new RoomList(retrievedRoomId, roomTitle,
created_at, username, numOfComments, filePath);
mRoomList.add(details);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MostRecentRooms Room;
//deliverResult(mRoomList);
return mRoomList;
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
loadInBackground();
//deliverResult(mRoomList);
}
#Override
public void onCanceled(List<RoomList> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
}
#Override
public void deliverResult(List<RoomList> data) {
// TODO Auto-generated method stub
Log.d("Deliver Result",""+data.size());
super.deliverResult(data);
}
#Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
}
#Override
protected void onStartLoading() {
// TODO Auto-generated method stub
if (mRoomList != null) {
//deliverResult(mRoomList);
}
super.onStartLoading();
}
#Override
protected void onStopLoading() {
// TODO Auto-generated method stub
cancelLoad();
}
}
Activity
public class MostRecentRooms extends ListActivity implements LoaderManager.LoaderCallbacks<List<RoomList>> {
// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;
// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;
HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;
// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;
// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;
// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
// buttons
Button back, loadMore, refresh;
Bitmap img_bitmap;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_most_recent_rooms);
mLoadManager = getLoaderManager();
mAdapter = new RoomListAdapter(this, getApplicationContext());
lv= getListView();
lv.setAdapter(mAdapter);
// back button
back = (Button) findViewById(R.id.backToMainMenu);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
// end back button
// get user id from View rooms class
if (getIntent().getExtras().getString("user_id_value") != null)
user_id = getIntent().getExtras().getString("user_id_value");
else
Log.e("Error", "Missing user_id");
mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);
//allRooms = new ArrayList<HashMap<String, String>>();
// allRooms = new ArrayList<String>();
// call class GetAllRooms
//new GetAllRooms().execute();
// get room_id
if (getIntent().getExtras().getString("room_id_to_send") != null)
room_id = getIntent().getExtras().getString("room_id_to_send");
else
Log.e("Error", "Missing room id");
loadMore = (Button) findViewById(R.id.loadMore);
loadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new LoadMoreRooms().execute();
// counter -= 5;
}
});
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mRoomList.clear();
allRooms.clear();
limit = 20;
tryme = 0;
img_bitmap.recycle();
//new GetAllRooms().execute();
}
});
}
/**
* This class get users status whether deleted or not
*/
class GetUserStatus extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
backGroundProcess(user_id);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("i is", "" + i);
if (i == 2) {
// decativatedPage();
Toast.makeText(getApplicationContext(), "noooo",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), RoomPage.class);
i.putExtra("room_id_to_send", clickedOnRoomId);
i.putExtra("user_id_value", user_id);
startActivity(i);
}
}
}// end class
private void backGroundProcess(String string) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", string));
json = jsonParser.makeHttpRequest(url2, "POST", params);
int success;
try {
success = json.getInt("success");
if (success == 1) {
i = 1;
Log.i("status", json.getString("message").toString());
} else if (success == 2) {
i = 2;
} else {
Log.d("Error", "Something went wrong");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Log.d("Tsg", "here");
RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
mRoomloader.forceLoad();
return mRoomloader ;
}
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
// TODO Auto-generated method stub
Log.i("tag","list loaded");
if(data != null){
mAdapter.SetData(data);
mAdapter.notifyDataSetChanged();
}
//mAdapter.SetData(data);
Log.i("Tag",""+data.size());
//lv.setAdapter(mAdapter);
}
#Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
// TODO Auto-generated method stub
Log.d("Loader", "Loader Reset");
mAdapter.SetData(null);
}
}
Adapter
public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;
public RoomListAdapter(Activity a, Context context) {
// TODO Auto-generated constructor stub
super(context, R.layout.viewroom_layout);
activity = a;
mInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(a.getApplicationContext());
//nRoomList = mRoomList;
//SetData(nRoomList);
}
public void SetData(List<RoomList> data) {
clear();
if (data != null) {
addAll(data);
}
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void setNotifyOnChange(boolean notifyOnChange) {
// TODO Auto-generated method stub
super.setNotifyOnChange(notifyOnChange);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi;
if (convertView == null) {
vi = mInflator.inflate(R.layout.viewroom_layout, null);
} else {
vi = convertView;
}
TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
TextView username = (TextView) vi.findViewById(R.id.creatorName);
TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
ImageView image = (ImageView) vi.findViewById(R.id.userPic);
//Log.d(TAG, "Within the room list adapter");
RoomList info = getItem(position);
room_id.setText(info.getmRoom_id());
room_title.setText(info.getmRoomTitle());
created_at.setText(info.getmCreated_at());
username.setText(info.getmUsername());
numOfComments.setText(info.getmNumberOfComments());
imageLoader.DisplayImage(info.getmFilePath(), image);
return vi;
}
}
with the help of venkat and monica i solved it didn't need the Syncadpter all i needed was a broadcast receiver this i did by
1) creating a broad cast intent when GCM receives the message
Intent intent1 = new Intent();
intent1.setAction("com.gcm.updatecame");
this.sendBroadcast(intent1);
2) in my Activity i register the receiver and create the class
filter1= new IntentFilter("com.gcm.updatecame");
registerReceiver(myReceiver, filter1);
Broadcast Receiver
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// write your code here to update the listview.
if(mLoadManager != null){
Reload.setVisibility(View.VISIBLE);
Reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLoadManager.destroyLoader(Loader_ID);
mAdapter.notifyDataSetChanged();
mAdapter.SetData(null);
mRoomList.clear();
mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
Reload.setVisibility(View.INVISIBLE);
}
});
}
}
};
Replace you onLoadFinished method with this one:
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
mAdapter = new RoomListAdapter(this, getApplicationContext());
mAdapter.SetData(data);
lv.setAdapter(mAdapter);
}
}
My listView is attached to an editText to allow the user to search through the listView. The problem is, the data filling my listView only shows after the user enters text into the editText and I would like the results to show before the user even types anything.
public class Search extends Activity {
EditText editText;
ListView listview;
int textlength = 0;
int width;
Button list;
Button filter;
CustomAdapter adapter;
Location userLoc;
private ArrayList<String> brand;
private ArrayList<String> size;
private ArrayList<String> price;
private ArrayList<Integer> percent;
private ArrayList<String> objID;
private ArrayList<String> store;
private ArrayList<String> address;
private ArrayList<Integer> distance;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<String> size_sort = new ArrayList<String>();
ArrayList<String> price_sort = new ArrayList<String>();
ArrayList<Integer> percent_sort = new ArrayList<Integer>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ArrayList<String> id_sort = new ArrayList<String>();
ArrayList<String> store_sort = new ArrayList<String>();
ArrayList<String> address_sort = new ArrayList<String>();
ArrayList<Integer> distance_sort = new ArrayList<Integer>();
Integer longitude;
Integer latitude;
ParseObject dealsObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
Parse.initialize(this, "vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY",
"4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ");
listview = (ListView) findViewById(R.id.listView1);
editText = (EditText) findViewById(R.id.editText1);
brand = new ArrayList<String>();
size = new ArrayList<String>();
price = new ArrayList<String>();
percent = new ArrayList<Integer>();
objID = new ArrayList<String>();
store = new ArrayList<String>();
address = new ArrayList<String>();
distance = new ArrayList<Integer>();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
userLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = (int) userLoc.getLongitude();
latitude = (int) userLoc.getLatitude();
userLoc.setLatitude(latitude);
userLoc.setLongitude(longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
getDeals();
adapter = new CustomAdapter(brand, size, price, percent, objID, store,
address, distance);
listview.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = editText.getText().length();
text_sort.clear();
size_sort.clear();
price_sort.clear();
percent_sort.clear();
image_sort.clear();
id_sort.clear();
store_sort.clear();
address_sort.clear();
distance_sort.clear();
for (int i = 0; i < brand.size(); i++) {
if (textlength <= brand.get(i).length()) {
if (editText
.getText()
.toString()
.equalsIgnoreCase(
(String) brand.get(i).subSequence(0,
textlength))) {
text_sort.add(brand.get(i));
size_sort.add(size.get(i));
price_sort.add(price.get(i));
percent_sort.add(percent.get(i));
id_sort.add(objID.get(i));
store_sort.add(store.get(i));
address_sort.add(address.get(i));
distance_sort.add(distance.get(i));
listview.setAdapter(new CustomAdapter(text_sort,
size_sort, price_sort, percent_sort,
id_sort, store_sort, address_sort,
distance_sort));
// Register onClickListener to Handle Click Events
// on Each Item
listview.setOnItemClickListener(new OnItemClickListener() {
//
// Argument position gives the index of item
// which is clicked
#Override
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
String brand = (String) text_sort
.get(position);
String size = (String) size_sort
.get(position);
String price = (String) price_sort
.get(position);
String objID = (String) id_sort
.get(position);
String store = (String) store_sort
.get(position);
String address = (String) address_sort
.get(position);
int percent = (int) percent_sort
.get(position);
Integer distance = distance_sort
.get(position);
Intent intent = new Intent(
"com.alpha.dealtap.DEALPAGE");
intent.putExtra("Brand", brand);
intent.putExtra("Size", size);
intent.putExtra("Price", price);
intent.putExtra("Percent", percent);
intent.putExtra("ID", objID);
intent.putExtra("Store", store);
intent.putExtra("Address", address);
intent.putExtra("Distance", distance);
System.out.println("My Selection: "
+ intent.toString());
startActivity(intent);
}
});
}
}
}
}
});
list = (Button) findViewById(R.id.sort);
Button map = (Button) findViewById(R.id.map);
filter = (Button) findViewById(R.id.filter);
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu popup = new PopupMenu(Search.this, list);
popup.getMenuInflater().inflate(R.menu.sortmenu,
popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getOrder() == 1) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
store.clear();
address.clear();
distance.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsPrice();
System.out.println(price);
} else if (item.getOrder() == 2) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
store.clear();
address.clear();
distance.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsPercent();
System.out.println(price);
} else if (item.getOrder() == 3) {
brand.clear();
size.clear();
price.clear();
percent.clear();
address.clear();
distance.clear();
objID.clear();
store.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsName();
System.out.println(brand);
} else {
System.out.println("Shit....Item is: "
+ item.getTitle());
}
Toast.makeText(Search.this,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
});
filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu popupTwo = new PopupMenu(Search.this, filter);
popupTwo.getMenuInflater().inflate(R.menu.filtermenu,
popupTwo.getMenu());
popupTwo.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getOrder() == 1) {
brand.clear();
size.clear();
price.clear();
percent.clear();
objID.clear();
address.clear();
distance.clear();
store.clear();
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
getDealsName();
} else {
Intent intent = new Intent(
"com.alpha.dealtap.STORESEARCH");
startActivity(intent);
}
return true;
}
});
popupTwo.show();
}
});
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.MAP"));
}
});
}
private void getDeals() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsPrice() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addDescendingOrder("Price");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsPercent() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addDescendingOrder("Percentage");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
private void getDealsName() {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Deals");
query.addAscendingOrder("Brand");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject dealsObject : objects) {
brand.add(dealsObject.getString("Brand"));
size.add(dealsObject.getString("Size"));
price.add("$" + dealsObject.getString("Price"));
percent.add(dealsObject.getInt("Percentage"));
objID.add(dealsObject.getObjectId());
store.add(dealsObject.getString("Store"));
address.add(dealsObject.getString("Address"));
Location location = new Location("");
location.setLatitude(dealsObject.getInt("Latitude"));
location.setLongitude(dealsObject.getInt("Longitude"));
distance.add((int) ((userLoc.distanceTo(location))/1609.34));
}
} else {
Log.v("Brand", "Error: " + e.getMessage());
}
}
});
}
class CustomAdapter extends BaseAdapter {
String[] data_text;
String[] size_text;
String[] price_text;
String[] id_text;
String[] store_text;
String[] address_text;
Integer[] percent_text;
Integer[] distance_text;
CustomAdapter(String[] text, String[] size, String[] price,
Integer[] percent, String[] id, String[] store,
String[] address, Integer[] distance) {
data_text = text;
size_text = size;
price_text = price;
percent_text = percent;
store_text = store;
address_text = address;
id_text = id;
distance_text = distance;
}
CustomAdapter(ArrayList<String> text, ArrayList<String> drinkSize,
ArrayList<String> price, ArrayList<Integer> percent,
ArrayList<String> objID, ArrayList<String> store,
ArrayList<String> address, ArrayList<Integer> distance) {
data_text = new String[text.size()];
size_text = new String[drinkSize.size()];
price_text = new String[price.size()];
percent_text = new Integer[percent.size()];
id_text = new String[objID.size()];
store_text = new String[store.size()];
address_text = new String[address.size()];
distance_text = new Integer[distance.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
size_text[i] = drinkSize.get(i);
price_text[i] = price.get(i);
percent_text[i] = percent.get(i);
id_text[i] = objID.get(i);
store_text[i] = store.get(i);
address_text[i] = address.get(i);
distance_text[i] = distance.get(i);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data_text.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.my_custom_dropdown, parent, false);
TextView textview = (TextView) row
.findViewById(R.id.textView_MainStore);
TextView size = (TextView) row.findViewById(R.id.textView_Size);
TextView price = (TextView) row.findViewById(R.id.textView_Price);
TextView percent = (TextView) row
.findViewById(R.id.textView_dist);
TextView store = (TextView) row
.findViewById(R.id.textView_Location);
textview.setText(data_text[position]);
size.setText(size_text[position]);
price.setText(price_text[position]);
percent.setText(String.valueOf(percent_text[position]) + "%");
store.setText(store_text[position]);
// Changes the color of the percent integer based on it's
// number...green if higher...red if lower
if (percent_text[position] >= 85)
percent.setTextColor(getResources().getColor(R.color.green));
else if (percent_text[position] >= 70
&& percent_text[position] <= 85)
percent.setTextColor(getResources().getColor(R.color.yellow));
else if (percent_text[position] >= 0
&& percent_text[position] <= 70)
percent.setTextColor(getResources().getColor(R.color.red));
return (row);
}
}
}
Sorry for the large block of code, but I've been stuck on this for a while.
Thank you!
Have you tried
adapter = new CustomAdapter(this, R.layout.listview, items);
setListAdapter(adapter);
rather than
listview.setAdapter(adapter);
? This worked for me when extending ArrayAdapter, rather than BaseAdapter which I had nothing but problems with. This tut helped immensely.
How to set background drawable, when clicking a dynamically created button like this :
I am using above code to create dynamic button and track click of specific button :
for (int i = 1; i<8; i++)
{
if(i==7)
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, "...");
btn.setTag(i);
linear_paging.addView(btn);
}
else
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, ""+i);
btn.setTag(i);
linear_paging.addView(btn);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Earned_New.this, v.getTag()+" clicked", Toast.LENGTH_SHORT).show();
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.black_rounded_background));
}
});
}
Finally I have got the solution. Please follow the below process to achieve the task and modify this according to your requirement, it will definitely help you:
1.) Do this in onResume() method :
new AsynDriverEarned().execute();
2.) CONST.EARNED_LISTVIEW_SIZE = 10// Number of records in a single page
3.) This is the inner class(AsyncTask)
class AsynDriverEarned extends AsyncTask<String, Void, String>{
ProgressDialog dialog=null;
JSONObject jsonObject;
JSONObject jsonUserDetail;
String response="";
String result="";
SharedPreferences settingPref;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog=new ProgressDialog(Earned_New.this);
dialog.setMessage("Loading...");
// dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
Log.i("DRIVER_ID", CONST.LOGIN_ID);
postParameters.add(new BasicNameValuePair("DRIVER_ID", CONST.LOGIN_ID));
try{
response=CustomHttpClient.executeHttpPost(CUSTOM_URL.Common_Url+"mobile_driver_earned.php", postParameters);
Log.i("response:", ""+response);
result = "OK";
if(response!=null){
try {
jsonObject = new JSONObject(response);
if(jsonObject.getBoolean("SUCCESS")){
pound_value_string = jsonObject.getString("TOTAL_EARNING");
result = "OK";
JSONArray jsonDriverArray = jsonObject.getJSONArray("DRIVER_ARRAY");
Log.i("jsonDriverArray:", ""+jsonDriverArray);
date_time_list = new ArrayList<String>();
drop_loc_list = new ArrayList();
passenger_names_list = new ArrayList();
total_earn_list = new ArrayList();
for (int i = 0; i < jsonDriverArray.length(); i++)
{
date_time_list.add(jsonDriverArray.getJSONObject(i).getString("BOOKING_DATE"));
drop_loc_list.add(jsonDriverArray.getJSONObject(i).getString("PASSENGER_DROP_LOCATION"));
passenger_names_list.add(jsonDriverArray.getJSONObject(i).getString("PASSENGER_NAME"));
total_earn_list.add(jsonDriverArray.getJSONObject(i).getString("EARNING"));
}
}
else{
result="FAILURE";
earner_error_message = jsonObject.getString("ERROR");
Log.i("earner_error_message", earner_error_message);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage();
}
}else{
result = "Timed Out!";
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// result = e.getMessage();
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
if(result.equalsIgnoreCase("OK"))
{
pound_value.setText(pound_value_string);
ArrayList<String> temp_date_time_list = new ArrayList<String>();
ArrayList<String> temp_drop_loc_list = new ArrayList();
ArrayList<String> temp_passenger_names_list = new ArrayList();
ArrayList<String> temp_total_earn_list = new ArrayList();
int start_number_of_records = (CONST.EARNED_LISTVIEW_SIZE*(1-1)); // no_of_records*tag_value
Log.i("start_number_of_records", ""+start_number_of_records);
int end_number_of_records = (((CONST.EARNED_LISTVIEW_SIZE*(1-1))+CONST.EARNED_LISTVIEW_SIZE)-1); //(no_of_records*tag_value+no_of_records)-1
Log.i("end_number_of_records", ""+end_number_of_records);
if (end_number_of_records<date_time_list.size())
{
Log.i("ENTER:", "FIRST");
for (int j = start_number_of_records; j < end_number_of_records+1; j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
else
{
Log.i("ENTER:", "SECOND");
for (int j = start_number_of_records; j < date_time_list.size(); j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
int num = date_time_list.size();
Log.i("num", ""+num);
int counter=1;
while(num>CONST.EARNED_LISTVIEW_SIZE)
{
num = num-CONST.EARNED_LISTVIEW_SIZE; // num = 32-5==27
counter++;
Log.i("counter", ""+counter);
continue;
}
for (int i = 1; i<counter+1; i++)
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, ""+i);
btn.setTag(i);
linear_paging.addView(btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_selector));
ArrayList<String> temp_date_time_list = new ArrayList<String>();
ArrayList<String> temp_drop_loc_list = new ArrayList();
ArrayList<String> temp_passenger_names_list = new ArrayList();
ArrayList<String> temp_total_earn_list = new ArrayList();
int start_number_of_records = (CONST.EARNED_LISTVIEW_SIZE*((Integer) v.getTag()-1)); // no_of_records*tag_value
// Log.i("start_number_of_records", ""+start_number_of_records);
int end_number_of_records = (((CONST.EARNED_LISTVIEW_SIZE*((Integer) v.getTag()-1))+CONST.EARNED_LISTVIEW_SIZE)-1); //(no_of_records*tag_value+no_of_records)-1
// Log.i("end_number_of_records", ""+end_number_of_records);
if (end_number_of_records<date_time_list.size())
{
Log.i("ENTER:", "FIRST");
for (int j = start_number_of_records; j < end_number_of_records+1; j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
else
{
Log.i("ENTER:", "SECOND");
for (int j = start_number_of_records; j < date_time_list.size(); j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
}
});
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(Earned_New.this);
builder.setMessage(earner_error_message);
builder.setCancelable(false);
LayoutInflater inflater = getLayoutInflater();
View vw = inflater.inflate(R.layout.custom_title, null);
builder.setCustomTitle(vw);
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
builder.show();
}
}
}
You can use the selector as drawable to that view.
Here is sample..
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/darker_gray" android:state_pressed="true"></item>
<item android:drawable="#android:color/darker_gray" android:state_selected="true"></item>
<item android:drawable="#android:color/darker_gray" android:state_checked="true"></item>
<item android:drawable="#android:color/transparent" ></item>
</selector>
You can change the colors in the above.
easily you can acheive this by taking RadioButton instead of Button. I will provide more info if you are unable to do that.
My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();