当我们单击gridView Item时出现ANR问题。我的代码在这里..
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainscreen);
setTheValue();
roll_dialog = new ProgressDialog(MainScreen.this);
roll_dialog.setMessage(" please wait while loading............");
roll_dialog.show();
startservice();
// Getting Current Location
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, mlocListener);
profile.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent intent=new Intent(MainScreen.this,MyProfile.class);
intent.putExtra("lat", latLoc);
intent.putExtra("long", longLoc);
startActivity(intent);
}
});
message.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
if(ChatScreen.kvp.size()!=0)
{
Intent intent=new Intent(MainScreen.this,GetOfflineMessages.class);
startActivity(intent);
}
else
{
showDialog(1);
}
}
});
chatroom.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
showDialog(3);
}
});
if(nearBySelected.equals("NearBy"))
{
nearBySelected="";
roll_dialog.setMessage(" please wait while loading............");
roll_dialog.show();
new Thread()
{
@Override
public void run()
{
Looper.prepare();
getUsers("NEARBY");
}
}.start();
}
else //if(Near.equals("1")|| Near.equals(""))
{
new Thread()
{
public void run()
{
getUsers("");
}
}.start();
}
checkInBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle mbundle = new Bundle();
Intent mintent =new Intent(MainScreen.this, CheckInScreen.class);
mbundle.putDouble("lat", latLoc);
mbundle.putDouble("langit", longLoc);
mbundle.putString("userId", prefName);
mintent.putExtras(mbundle);
startActivity(mintent);
}
});
adMob.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainScreen.this, AdMobScreen.class));
}
});
}
@Override
public void onResume()
{
super.onResume();
Near="";
Far="";
// do my stuff
Log.e("resumed","wassup");
if(ChatScreen.kvp.size()!=0)
{
message.setText(""+ChatScreen.kvp.size());
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
timer.cancel();
new WebServiceCallTask().execute();
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//goOffline();
}
public void goOffline()
{
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_ID, "0");
String url = "http://dotnet4.peaceofmind.in/ms/ChestMeetAndMeet/ChestMeetAndMeatServices.asmx/GetUserListSpecificUser";
Log.e("url", "" + url);
HttpClient httpclient = new DefaultHttpClient();
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userid",""+prefName));
nameValuePairs.add(new BasicNameValuePair("onlinestatus","false"));
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
}catch(Exception e)
{
e.printStackTrace();
}
}
/*it is main web services all app running from here*/
public void getUsers(final String getNearBy)
{
String flag="";
LocationManager lm;
LocationListener locationListener;
Location location = null, gps_loc;
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
prefName = myPrefs.getString(MY_ID, "0");
if(getNearBy.equalsIgnoreCase("NEARBY"))
{
try
{
//mapController = mapView.getController();
myLocation = new MyLocation()
{
public void locationClick()
{
myLocation.getLocation(MainScreen.this, locationResult);
}
LocationResult locationResult = new LocationResult()
{
@Override
public void gotLocation(final Location location)
{
if(location != null)
{
neabylatitude = location.getLatitude();//*1E6
nearbylongitute = location.getLongitude();//*1E6
origin1 = Double.toString(neabylatitude);
origin2= Double.toString(nearbylongitute);
url="http://dotnet4.peaceofmind.in/ms/ChestMeetAndMeet/ChestMeetAndMeatServices.asmx/UserListNearByWithSpecificUserId?sLatitude="+neabylatitude+"&sLongitude="+nearbylongitute+"&iRadius=10"+"&userid="+prefName;
System.out.println("near url"+url);
if(getNearBy.equalsIgnoreCase("NEARBY"))
handelLocation("NEARBY");
}
}
};
};
myLocation.locationClick();
} catch (Exception e)
{
}
}
else
handelLocation(getNearBy);
}
private void handelLocation(String getNearBy)
{
Message msg = handler.obtainMessage();
if(getNearBy.equalsIgnoreCase("FRIEND"))
{
url="http://dotnet4.peaceofmind.in/ms/ChestMeetAndMeet/ChestMeetAndMeatServices.asmx/GetUserFriendList?sUserId="+prefName;
}
if(!getNearBy.equalsIgnoreCase("NEARBY") && !getNearBy.equalsIgnoreCase("FRIEND"))
{
url="http://dotnet4.peaceofmind.in/ms/ChestMeetAndMeet/ChestMeetAndMeatServices.asmx/GetUserListSpecificUser?userid="+prefName+"&onlinestatus=true";
}
try
{
int i;
char[] buffer = new char[1024];
Writer writer = new StringWriter();
URL url1= new URL(url);
HttpClient client = new DefaultHttpClient();
//HttpEntity entity;
HttpGet method= new HttpGet();
method.setURI(new URI(url));
//HttpRequest request=new
HttpResponse response=client.execute(method);
HttpEntity entity=response.getEntity();
InputStream stream=entity.getContent();
//InputStreamReader reader=new InputStreamReader(entity.getContent());
Log.e("b4 execute in login","aditya");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
// Get the XMLReader of the SAXParser we created.
XMLReader xr = sp.getXMLReader();
// Create a new ContentHandler and apply it to the XML-Reader
//UserListHandler myExampleHandler = new UserListHandler();
MainScreenHandler myExampleHandler = new MainScreenHandler();
xr.setContentHandler(myExampleHandler);
// Parse the xml-data from our URL.
xr.parse(new InputSource(stream));
// Parsing has finished.
ArrayList<MainScreenObject> nearByArray = myExampleHandler.getnearbydicSearch();
msg.obj = nearByArray;
msg.arg1 = SUCCESS;
}
catch(Exception e)
{
msg.arg1 = FAILURE;
Log.e("inside catch","io exception"+e.getStackTrace());
Log.e("inside catch","io exception"+e.getMessage());
}
handler.sendMessage(msg);
}
//recieve Message here
public void receiveMessage()
{
Message msg = receivedhandler.obtainMessage();
String flag="";
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_ID, "0");
Log.e("getlogin id ","1:"+prefName);
String url="http://dotnet4.peaceofmind.in/ms/ChestMeetAndMeet/ChestMeetAndMeatServices.asmx/ReceiveMessage?iReceiverId="+prefName;
try
{
Log.d("url","1"+url);
int i;
char[] buffer = new char[1024];
Writer writer = new StringWriter();
URL url1= new URL(url);
HttpClient client = new DefaultHttpClient();
HttpGet method= new HttpGet();
method.setURI(new URI(url));
//HttpRequest request=new
Log.e("b4 execute in login","1");
HttpResponse response=client.execute(method);
Log.e("b4 execute in login","2");
HttpEntity entity=response.getEntity();
Log.e("b4 execute in login","3");
InputStream stream=entity.getContent();
Log.e("b4 execute in login","3");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
// Get the XMLReader of the SAXParser we created.
XMLReader xr = sp.getXMLReader();
ReceiveMessageHandler myExampleHandler = new ReceiveMessageHandler();
xr.setContentHandler(myExampleHandler);
xr.parse(new InputSource(stream));
msg.arg1 = RECIEVESUCCESS;
msg.obj = myExampleHandler.getReciveMessageList();
}
catch(Exception e)
{
msg.arg1=RECIEVEFAILURE;
Log.e("inside catch","io exception");
}
Log.d("getReturn",""+RegistrationSiteList.registrationResponse);
//return flag;
receivedhandler.sendMessage(msg);
}
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
private Activity activity;
private String[] data;
public ImageLoader imageLoader;
private LayoutInflater inflater;
public ImageAdapter(Context c,Activity a,String[] d)
{
mContext = c;
data=d;
activity=a;
imageLoader=new ImageLoader(a);
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return data.length;
}
public Object getItem(int position)
{
return data[position];
}
public class ViewHolder
{
public TextView name,onlinestatusgreen;
public ImageView image;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
String onlinestauts ="";
ViewHolder holder;
String Username="";
if(convertView==null)
{
vi = inflater.inflate(R.layout.loginstatus, null);
holder=new ViewHolder();
holder.name=(TextView)vi.findViewById(R.id.mainname);
holder.name.setTextColor(R.color.black);
holder.image=(ImageView)vi.findViewById(R.id.image);
holder.onlinestatusgreen = (TextView)vi.findViewById(R.id.onlinesataus);
vi.setLayoutParams(new GridView.LayoutParams(85, 85));
vi.setPadding(8, 8, 8, 8);
vi.setBackgroundResource(R.color.white);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(userlist.size()>position)
{
String msgstatus = userlist.get(position).getMaritalStatus();
String str ="1"+msgstatus;
if(str.equals("1No Friend List Available"))
{
nofriendlistfound=true;
onlinestauts ="1";
}
else
{
onlinestauts = userlist.get(position).getOnline();
Username =userlist.get(position).getFirstName();
}
}
holder.name.setText(Username);
onlinestauts =onlinestauts+"1";
if(onlinestauts.equalsIgnoreCase("true1"))
{
holder.onlinestatusgreen.setVisibility(View.VISIBLE);
}
else
{
holder.onlinestatusgreen.setVisibility(View.INVISIBLE);
}
if(data.length!=0 && data[position]!=null && !data[position].equals(""))
{
holder.image.setTag(data[position]);
imageLoader.DisplayImage(data[position],MainScreen.this,holder.image);
}
else
{
holder.image.setVisibility(View.INVISIBLE);
}
return vi;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.meat:
if(event.getAction() == MotionEvent.ACTION_DOWN){
meat.setBackgroundResource(R.drawable.meat_h);
Intent intent=new Intent(MainScreen.this,MeatAnimation.class);
startActivity(intent);
finish();
}
else{
if(event.getAction() == MotionEvent.ACTION_UP)
meat.setBackgroundResource(R.drawable.meat);
}
break;
case R.id.mainglobal:
if(event.getAction() == MotionEvent.ACTION_DOWN){
global.setBackgroundResource(R.drawable.far_h);
// TODO Auto-generated method stub
roll_dialog.setMessage(" please wait while loading............");
roll_dialog.show();
new Thread()
{
@Override
public void run()
{
getUsers("");
}
}.start();
}
else{
if(event.getAction() == MotionEvent.ACTION_UP)
global.setBackgroundResource(R.drawable.far);
}
break;
case R.id.friend:
if(event.getAction() == MotionEvent.ACTION_DOWN){
friends.setBackgroundResource(R.drawable.friends_h);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_ID, "0");
if(prefName.equals("0"))
{
AlertDialog alertDialog = new AlertDialog.Builder(MainScreen.this).create();
alertDialog.setMessage("Please First make your account");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
//alertDialog.setIcon(R.drawable.icon);
alertDialog.show();
}
else
{
roll_dialog.setMessage(" please wait while loading............");
roll_dialog.show();
new Thread()
{
@Override
public void run()
{
Looper.prepare();
getUsers("FRIEND");
}
}.start();
}
}
else{
if(event.getAction() == MotionEvent.ACTION_UP)
friends.setBackgroundResource(R.drawable.freinds);
}
break;
case R.id.mainmrpec:
if(event.getAction() == MotionEvent.ACTION_DOWN){
mrPec.setBackgroundResource(R.drawable.pec_h);
Intent intent=new Intent(MainScreen.this,SendMail.class);
startActivity(intent);
finish();
}
else{
if(event.getAction() == MotionEvent.ACTION_UP)
mrPec.setBackgroundResource(R.drawable.pec);
}
break;
case R.id.mainnearby:
if(event.getAction() == MotionEvent.ACTION_DOWN){
nearBy.setBackgroundResource(R.drawable.near_h);
roll_dialog.setMessage(" please wait while loading............");
roll_dialog.show();
new Thread()
{
@Override
public void run()
{
Looper.prepare();
getUsers("NEARBY");
}
}.start();
}
else{
if(event.getAction() == MotionEvent.ACTION_UP)
nearBy.setBackgroundResource(R.drawable.near);
}
}
return false;
}
protected Dialog onCreateDialog(int id)
{
if(id == NO_NEW_MESSAGES)//Show message on Sign out button click.
{
return new AlertDialog.Builder(this)
.setTitle("Sorry")
.setMessage("No messages")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}
)
.create();
}
if(id ==3)
{
return new AlertDialog.Builder(this)
.setMessage("'Please buy our full version to unlock SCHNACK,\n undress all men,and help us \n with the cost,it's only 2$'")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}
)
.create();
}
if(id ==10)
{
return new AlertDialog.Builder(this)
.setMessage("Please,First Create Profile")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}
)
.create();
}
if(id ==4)
{
return new AlertDialog.Builder(this)
.setMessage("No Friend List Available")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}
)
.create();
}
return null;
}
private void setTheValue()
{
meat=(Button)findViewById(R.id.meat);
meat.setOnTouchListener(this);
chatroom=(ImageView)findViewById(R.id.chatroom);
friends=(Button)findViewById(R.id.friend);
friends.setOnTouchListener(this);
profile=(TextView)findViewById(R.id.profile);
nearBy=(Button)findViewById(R.id.mainnearby);
nearBy.setOnTouchListener(this);
mrPec=(Button)findViewById(R.id.mainmrpec);
mrPec.setOnTouchListener(this);
global=(Button)findViewById(R.id.mainglobal);
global.setOnTouchListener(this);
message=(TextView)findViewById(R.id.messages);
checkInBtn = (ImageButton) findViewById(R.id.checkInBtn);
adMob= (TextView) findViewById(R.id.adMob);
}
private void startservice()
{
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
new Thread()
{
public void run()
{
Looper.prepare();
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_ID, "0");
if(!prefName.equalsIgnoreCase("0"))
{
receiveMessage();
}
}
}.start();
Log.e("b4 setmessage","1:"+ChatScreen.kvp.size());
}
}, 0, INTERVAL);
}
public void getMeassageDetails()
{
if(objrReceiveMessageSiteList.size()!=0)
{
for(int i=0;i<objrReceiveMessageSiteList.size();i++)
{
KeyValuePair keysValues=new KeyValuePair();
Log.e("added","2");
keysValues.setLatitude(objrReceiveMessageSiteList.get(i).getLatitude());
keysValues.setLongitude(objrReceiveMessageSiteList.get(i).getLongitude());
keysValues.setSenderId(objrReceiveMessageSiteList.get(i).getSenderId());
keysValues.setMessageType(objrReceiveMessageSiteList.get(i).getMessageType());
keysValues.setMessage(objrReceiveMessageSiteList.get(i).getMessage());
keysValues.setTimeStamp(objrReceiveMessageSiteList.get(i).getTimeStamp());
keysValues.setSenderUserName(objrReceiveMessageSiteList.get(i).getSenderUserName());
keysValues.setSenderFirstName(objrReceiveMessageSiteList.get(i).getSenderFirstName());
ChatScreen.kvp.add(keysValues);
Log.e("added","kvp size"+ChatScreen.kvp.size());
}
message.setText(""+ChatScreen.kvp.size());
}
}
public void showUsers()
{
//site=new UserListSiteList();
imageurl = new String[userlist.size()];//[(site.getProfileImage().size())];
int size=userlist.size();//site.getProfileImage().size();
//Log.e("size",""+size);
int matchUserId;
for (int i = 0; i<size; i++)
{
imageurl[i] =userlist.get(i).getProfileImage(); ;//site.getProfileImage().get(i);
}
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,MainScreen.this,imageurl));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
String seletedmemberUserID="";
String seletedmemberUserName="";
String statusvalue="";
if(userlist.size()>position)
{
seletedmemberUserID = userlist.get(position).getUserId();
seletedmemberUserName = userlist.get(position).getFirstName();
statusvalue = userlist.get(position).getOnline();
}
Bundle objbundle = new Bundle();
Intent intent=new Intent(MainScreen.this,ProfileScreen.class);
objbundle.putInt("position",position);
objbundle.putString("selectuserid",seletedmemberUserID);
objbundle.putString("selectusername",seletedmemberUserName);
objbundle.putDouble("userlattiute",latLoc);
objbundle.putDouble("userlongitute",longLoc);
objbundle.putString("status",statusvalue);
intent.putExtras(objbundle);
startActivity(intent);
}
});
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
String lat_long = loc.getLatitude() + "," + loc.getLongitude();
lat_long = "28.6146643,77.3714361";
MyConstant.GlobalURL = MyConstant.CHECK_IN_URL+lat_long+"&radius=500&sensor=false&key=05qzDuEPI79pO6b_3kbDiikhFYO6uSQFo94qQpA";
latLoc=loc.getLatitude();
longLoc=loc.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}/* End of Class MyLocationListener */
class WebServiceCallTask extends AsyncTask<Void, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(MainScreen.this);
// can use UI thread here
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
goOffline();
return null;
}
// can use UI thread here
protected void onPostExecute(final String result) {
}
}
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if(msg.arg1==SUCCESS)
{
roll_dialog.dismiss();
userlist = (ArrayList<MainScreenObject>)msg.obj;
String value = userlist.get(0).getMaritalStatus();
String str="1"+value;
showUsers();
if(userlist.size()==0 || str.equalsIgnoreCase("1No Friend List Available"))
{
showDialog(4);
}
}
}
};
private Handler receivedhandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if(msg.arg1!=RECIEVEFAILURE)
{
objrReceiveMessageSiteList =(ArrayList<ReceiveMessageSiteList>)msg.obj;
if(objrReceiveMessageSiteList.size()!=0)
{
for(int i=0;i<objrReceiveMessageSiteList.size();i++)
{
KeyValuePair keysValues=new KeyValuePair();
Log.e("added","2");
keysValues.setLatitude(objrReceiveMessageSiteList.get(i).getLatitude());
keysValues.setLongitude(objrReceiveMessageSiteList.get(i).getLongitude());
keysValues.setSenderId(objrReceiveMessageSiteList.get(i).getSenderId());
keysValues.setMessageType(objrReceiveMessageSiteList.get(i).getMessageType());
keysValues.setMessage(objrReceiveMessageSiteList.get(i).getMessage());
keysValues.setTimeStamp(objrReceiveMessageSiteList.get(i).getTimeStamp());
keysValues.setSenderUserName(objrReceiveMessageSiteList.get(i).getSenderUserName());
keysValues.setSenderFirstName(objrReceiveMessageSiteList.get(i).getSenderFirstName());
ChatScreen.kvp.add(keysValues);
}
message.setText(""+ChatScreen.kvp.size());
}
}
}
};
我已经使用 AsyncTask 而不是接收由 Timer 9 以固定间隔调用的处理程序。