This is the class i gain a null pointer from it points to line 65.
public class searchlist extends ListActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new loadSomeStuff().execute();
}
public class loadSomeStuff extends AsyncTask<String, Integer, String[]>
{
ProgressDialog dialog;
protected void onPreExecute()
{
dialog = new ProgressDialog(searchlist.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMax(100);
dialog.show();
}
#Override
protected String[] doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i =0; i<20; i++)
{
publishProgress(5);
try
{
Thread.sleep(80);
} catch(InterruptedException e)
{
e.printStackTrace();
}
}
dialog.dismiss();
int loops = search_page.returnlooped();
int[] teacup = search_page.returnNumArray();
sqlStuff searching = new sqlStuff(searchlist.this);
String[] IDSysNames = searching.getIDSysName();
searching.close();
String[] resultList = new String[loops];
for(int i=0; i < loops; i++ )
{
if(IDSysNames[teacup[i]] != null)
{
resultList[i].equals(IDSysNames[teacup[i]]); //Line 65
}
}
setListAdapter(new ArrayAdapter<String>(searchlist.this, android.R.layout.simple_list_item_1, resultList));
return null;
}
protected void onProgressUpdate(Integer...progress)
{
dialog.incrementProgressBy(progress[0]);
}
}
This is the getIDSysname class used by the class above.
public String[] getIDSysName()
{
String[] result = new String[0];
try
{
String[] columns = new String[] {KEY_SYSNAME};
Cursor c = ChemPal.query(DATABASE_TABLE, columns, null, null, null, null, null);
Log.d("SqlDStuff", "Cursor count: "+c.getCount());
int iSysName = c.getColumnIndex(KEY_SYSNAME);
int i = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
i++;
}
result = new String[i];
i = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result[i] = c.getString(iSysName);
i++;
}
}
catch(Exception e)
{
}
return result;
}
If anything else is needed please ask in the comments because this is frustrating me at the moment. Thank you
You've allocated an array of strings:
String[] resultList = new String[loops];
for (int i=0; i < loops; i++ ) {
if (IDSysNames[teacup[i]] != null) {
resultList[i].equals(IDSysNames[teacup[i]]); //Line 65
There aren't any strings in it upon which to call equals.
dialog.dismiss();
you can not call dismiss on doInBackground(). Every method pertinent to the UI Thread has to be called on the UI Thread.
try with:
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
setListAdapter(new ArrayAdapter(searchlist.this, android.R.layout.simple_list_item_1, resultList));
I had to move this method to the onCreate(); and i had to retrun the resultList value via a method called onPostExecute.
Turns out the log cat was making up the null pointer don't know why . Thanks guys but i got it now.
Related
Am displaying random checkboxes from remote server and if a user checks a checkbox then am storing that value in sqlite database and on the next loading am checking whether that value is present in database or not and if its present then bydefault it will check the checkbox. my problem is everytime i try to insert a value to sqlite it always takes the first checked checkbox value. But if I use a toast to check my code am getting the respective checkbox value. but that doesn't work with sqlite
Here is how am displaying a checkbox and setting on clicklistener
rl = (LinearLayout) getView().findViewById(R.id.linearmain);
HashMap<String, String> resultp = new HashMap<String, String>();
sqlcon = new SQLController(context);
sqlcon.open();
CheckBox[] cb = new CheckBox[arraylist.size()];
Cursor c = sqlcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
for(int i = 0; i < arraylist.size(); i++) {
resultp = arraylist.get(i);
cb[i] = new CheckBox(getActivity());
cb[i].setText(resultp.get(Fltrsubfragment.SUB));
cb[i].setId(i);
cb[i].setOnClickListener(handleOnClick(cb[i]));
rl.addView(cb[i]);
for ( int ikv = 0; ikv < rows; ikv++) {
// inner for loop
for (int j = 0; j < cols; j++) {
String iv;
iv=c.getString(j);
if(iv==null){
Toast.makeText(context, " Empty " + rows, Toast.LENGTH_LONG).show();
}
else if(iv.equals(cb[i].getText().toString())){
cb[i].setChecked(true);
Toast.makeText(context, " Checked " + rows, Toast.LENGTH_LONG).show();
}
else{
cb[i].setChecked(false);
}
}
}
View.OnClickListener handleOnClick(final CheckBox button) {
return new View.OnClickListener() {
public void onClick(View v) {
if(button.isChecked()){
if(barraylist.contains(button.getText().toString())){
Toast.makeText(context, " Already added " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
brandarraylist.add(button.getText().toString());
name=button.getText().toString();
new MyAsync().execute();
Toast.makeText(context, " Stored " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
else{
if(barraylist.contains(button.getText().toString()))
{
barraylist.remove(button.getText().toString());
name=button.getText().toString();
new MyAsyncS().execute();
sqlcon.deleteTData(button.getText().toString());
Toast.makeText(context, "Removed this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Unchecked this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
};
AsyncTask code to insert value
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(context);
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
if(name==null){
return null;
}
// inserting data
else{
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(name);
sqlcon.close();
// BuildTable();
return null;
}
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
here is the insertData code
public void insertData(String name) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(MyDbHelper.LT_VAL, name);
database.insert(MyDbHelper.LTE, null, cv);
}
Please suggest where am making the mistake.
Inside new MyAsync().execute(); put name:
I recommend using .trim() on all user input. You could easily chain this to:
name=button.getText().toString().trim();
new MyAsync().execute(name);
Then get it by using:
#Override
protected String doInBackground(String... params) {
String name = params[0];
We ruled out context by changing the code to:
#Override
protected String doInBackground(String ... params) {
String name = params[0];
if(name==null){
return null;
}else{
return name;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(result);
sqlcon.close();
// BuildTable();
PD.dismiss();
}
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
So I have a listview where I wanted to sort the NumberOfRecords in descending order. I have a custom array adapter but I called my sorting class before I place a data in my ArrayList, this my Asynctask receiving JSON:
public class SampleListTask extends AsyncTask<String, Void, String> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SampleActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... path) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.d(Constant.TAG_RANKING, path[0]);
String apiRequestReturn = UtilWebService.getRequest(path[0]);
if (apiRequestReturn.equals("")) {
Log.d(Constant.TAG_SAMPLE, "WebService request is null");
return null;
} else {
Log.d(Constant.TAG_SAMPLE, "WebService request has data");
return apiRequestReturn;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
application.shortToast("No data found from server");
} else {
try {
JSONObject sampleObject = new JSONObject(result);
JSONArray jsonArray = sampleObject
.getJSONArray(Constant.TAG_SAMPLE);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
sample = new ArraySample();
sample.setId(objJson.getInt(Constant.TAG_SONGID));
sample.setThumbUrl(objJson
.getString(Constant.TAG_IMAGEURL));
sample.setTitle(objJson
.getString(Constant.TAG_NAME));
sample.setArtist(objJson
.getString(Constant.TAG_ARTIST));
sample.setDuration(Utility
.changeStringTimeFormat(objJson
.getString(Constant.TAG_MUSICLENGTH)));
sample.setNumberOfRecords(objJson
.getString(Constant.TAG_NUMBEROFRECORDS));
Collections.sort(sampleList, new SortByRecordNumber()); // This where I call the class
sampleList.add(sample);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
public void setAdapterToListview() {
objRowAdapter = new RowAdapterSample(getApplicationContext(),
R.layout.item_sample, sampleList);
sampleListView.setAdapter(objRowAdapter);
}
}
And here's my sorting class:
public class SortByRecordNumber implements Comparator {
public int compare(Object o1, Object o2) {
ArraySample p1 = (ArraySample) o1;
ArraySample p2 = (ArraySample) o2;
return p2.getNumberOfRecords().compareTo(p1.getNumberOfRecords());
}
}
But the result I'm getting is:
5
15
14
0
0
Is my sorting implementation wrong? Or should I parse it to Integer before return?
You can use the following code to sort your integer list is descending order.Here we are overriding compare() so that it sorts in descending order.
//sort list in desc order
Collections.sort(myIntegerList, new Comparator<Integer>() {
public int compare(Integer one, Integer other) {
if (one >= other) {
return -1;
} else {
return 1;
}
}
});
Hope it helps.
Try with this Comparator.
Comparator objComparator = new Comparator() {
public int compare(Object o1, Object o2) {
int no1 = Integer.parseInt((String) o1);
int no2 = Integer.parseInt((String) o2);
return no1 < no2 ? -1 : no1 == no2 ? 0 : 1;
}
};
Collections.sort(myIntegerList, objComparator);
Okay, so I solved this by replacing the:
p2.getNumberOfRecords().compareTo(p1.getNumberOfRecords())
to:
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
Integer.parseInt(string)
and get the true value of the number string.
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();