Related
In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();
Through this code I am trying to send a value from one Activity to another activity. But I am getting a null value in the other Actvity. In the doinbackground method, I am getting the value of Status and Reason but in onPostexecute I am not getting value. Any idea why?
public class Serchphonenumber extends Activity implements OnClickListener {
EditText phonenumber;
ImageView backbutton;
Button search;
String _url;
String Username;
String Password;
String Circlearea;
String Phonenumber;
JSONfunctions _jparser = new JSONfunctions();
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.act_serchphonenumber);
backbutton = (ImageView) findViewById(R.id.searchstatus_imgBack);
search = (Button) findViewById(R.id.searchstatus_btnSearch);
phonenumber = (EditText) findViewById(R.id.searchstatus_editMobile);
Intent intent = getIntent();
Username = intent.getStringExtra("Username");
Password = intent.getStringExtra("Password");
Circlearea = intent.getStringExtra("Circlearea");
search.setOnClickListener(this);
backbutton.setOnClickListener(this);
search.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.searchstatus_btnSearch) {
if (phonenumber.toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Entere Your Phone Number", 10000).show();
}
new a().execute();
}
if (v.getId() == R.id.imageView1) {
{
finish();
}
}
}
class a extends AsyncTask<String, String, String> {
public String Status;
public String Reason;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Serchphonenumber.this);
pDialog.setTitle("Serching");
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Phonenumber = phonenumber.getText().toString().trim();
_url = "http://182.71.212.107:8080/api/values/status?userId="
+ Username + "&" + "password=" + Password + "&" + "circle="
+ Circlearea + "&" + "mobile=" + Phonenumber;
Log.d("value,************", _url);
//
try {
String json = HttpHitter.ExecuteData(_url);
JSONArray _jarray = new JSONArray(json);
// _jparser.getJSONfromURL(_url);
JSONObject _jobject = _jarray.getJSONObject(0);
Status = _jobject.getString("Status");
Reason = _jobject.getString("Reason");
Log.e("Response+++", Status);
Log.e("Reason+++", Reason);
// JSONObject jsn = _jobject.getJSONObject("responseData");
//
// runOnUiThread(afterParsing);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pDialog.dismiss();
//
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (Status.equalsIgnoreCase("ACCEPTED")) {
Intent intent = new Intent(Serchphonenumber.this,
Serchresult.class);
intent.putExtra("Status", Status);
intent.putExtra("Reason", Reason);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Worng", 1000).show();
}
}
}
}
Use this in onCreate() methed on activity class
String Status= getIntent().getExtras().getString("Status");
String Reason= getIntent().getExtras().getString("Reason");
You can use intents,which are messages sent between activities in intent you can put sort data like String, int, etc.
in activity1
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
activity2
Intent intent = getIntent();
String message = bundle.getString("message");
i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a custom list view that is getting data from server and changing its content after each 3 seconds.this list view i am using for showing the visitor list who are visiting the site.Each row of list contains ipaddress,statustext,duration time,noofvisit and button text and data is updating and changing in list this part is working fine.For showing this list i am writing custom adapter for this.
Actually i have an issue i have to show the row on the top if status text is chat request.How can i do this?can anyone help me?
Actually i am using tabhost after login screen tabhost contains four tabs.First used for monitoring window that show list of visitor and other are chat window,operatorlist and controls.
As i define above if i got status chat request then that row should appear on the top and will contains two button Accept and deny and on accept button click a window will open for chat and deny will use for refusing chat.
Can anyone help me for solving this issue?
my code is following
public class BaseActivity extends Activity {
private ListView list =null;
private NotificationManager mNotificationManager;
private final int NOTIFICATION_ID = 1010;
public static Timer timer = new Timer();
private String response;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText,StatusText;
private ArrayList<String> NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
private CustomAdapter adapter;
public static String from,sessionid,id,text,iptext,status,temo;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler;
public void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
try {
Log.i("UPDATE", "Handler called");
list.invalidateViews();
playSound3();
} catch(Exception e) {
Log.e("UPDATE ERROR", "error");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
//list.addView("chat request", 0);
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 7000);
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
logoutFromServer();
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private void playSound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_AllOnline;
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
//System.out.println("Output of httpResponse:"+response);
String result = response;
result = response;
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String[] temp = result.split(delimiter2);
operatorDetail = result.split(delimiter1);
if(temp.length==7){
String visitorString = temp[0];
String strSound = temp[3];
String strCSRmsgOrChatTrans = temp[4];
String stroperator = temp[5];
String strvisitor = temp[1];
visitorString = visitorString.trim();
if(!(visitorString.equals(""))||(visitorString.equalsIgnoreCase("No Visitors online")||(visitorString.equalsIgnoreCase("No Users Online")))){
operatorDetail = result.split(delimiter1);
//sizeoflist =operatorDetail.length;
}
else{
sizeoflist = 0;
}
}
else{
sizeoflist = operatorDetail.length;
}
//System.out.println("operatordetail length"+operatorDetail.length);
System.out.println("firstresponse================"+operatorDetail[0]);
if(operatorDetail[0].equalsIgnoreCase("logout")){
sizeoflist = 0;
System.exit(0);
finish();
}
if(temp[0].equalsIgnoreCase("No Users Online")){
if(temp[1].equalsIgnoreCase("0")){
sizeoflist =0;
}
else if(temp[1].length()>0){
sizeoflist = 0;
}
else if(temp[0].equalsIgnoreCase("")){
sizeoflist = 0;
}
sizeoflist =0;
}
else{
sizeoflist =operatorDetail.length;
}
//operatorDetail = result.split(delimiter1);
//--------Getting the size of the list---------------------
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
//playsound3();
noofchat =0;
list.setAdapter(new CustomAdapter(BaseActivity.this));
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setFastScrollEnabled(true);
//list.setSelected(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
});
}
else {
//ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//------------------------Getting the notification of no.of visitor on the site---------------------------
private void triggerNotification() {
// TODO Auto-generated method stub
CharSequence title = "No Of visitors";
CharSequence message = "New visit";
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, noofvisitors[0], System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, L2STest.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(BaseActivity.this, title, noofvisitors[0], pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
playsound4();
}
public void completed() {
//remove the notification from the status bar
mNotificationManager.cancel(NOTIFICATION_ID);
}
private void playsound4() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
//-----------------Logout from server--------------------
private void logoutFromServer() {
// TODO Auto-generated method stub
final String url ="http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_LOGOUT;
final HashMap<String, String> postParameters = new HashMap<String, String>();
try{
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
}catch(Exception e){
e.printStackTrace();
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// notificationManager.cancelAll();]
System.out.println(response);
showAlert1();
//getSharedPreferences(Main.PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
Log.e(DEB_TAG, response);
//System.exit(0);
Intent intent = new Intent(BaseActivity.this,Main.class);
startActivity(intent);
//closeHandler();
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//----------------------Logout alert when user click on logout button------------------
private void showAlert1() {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "You have Successfully logout.";
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.show();
}
//-------------------Play sound3 when any new user visit----------------
private void playsound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//------------------The adapter class------------------------------
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.notifyDataSetChanged();
SessionText.clear();
IPText.clear();
DurationText.clear();
StatusText.clear();
NoOfVisit.clear();
ButtonText.clear();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* #see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
//holder.accept = (Button) convertView.findViewById(R.id.btnaccept);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
holder.invite.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
for(int i=0;i<operatorDetail.length;i++){
if(operatorDetail!=null){
//System.out.println("Operator res=============="+operatorDetail[i]);
operatorList = operatorDetail[i].split(delimiter);
try{
if(operatorList[0]!=null){
SessionText.add(operatorList[0]);
sessionid = operatorList[0];
}
else{
onStart();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[1]!=null){
IPText.add(operatorList[1]);
iptext = operatorList[1];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[4]!=null){
DurationText.add(operatorList[4]);
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[3]!=null){
StatusText.add(operatorList[3]);
status = operatorList[3];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[2]!=null){
NoOfVisit.add(operatorList[2]);
}
else{
System.out.println("Oplst is null");
}
}catch(Exception e){
e.printStackTrace();
}
//ButtonText.add(operatorList[6]);
try{
if(IPText!=null){
holder.IP.setText(IPText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(DurationText!=null){
holder.duration.setText(DurationText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(StatusText!=null){
holder.status.setText(StatusText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(NoOfVisit!=null){
holder.noOfVisit.setText(NoOfVisit.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
//----------------If status is chat request then check for this-----------------
try{
if(StatusText.get(position).equalsIgnoreCase("chat request")){
//playsound();
playsound();
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.deny.setText("Deny");
convertView.bringToFront();
convertView.setFocusableInTouchMode(true);
convertView.setSelected(true);
//convertView.setFocusable(true);
convertView.requestFocus();
convertView.clearFocus();
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
try{
chatRequest(IPText.get(position), SessionText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
Intent i = new Intent(BaseActivity.this,Chat1.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
try{
i.putExtra("SessionText",SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
i.putExtra("StatusText",StatusText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
startActivity(i);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText!=null){
callToServer(SessionText.get(position));
}
else{
System.out.println("null");
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
catch(Exception e){
e.printStackTrace();
}
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText.get(position)!=null){
refuseToServer(SessionText.get(position));
holder.deny.setVisibility(View.INVISIBLE);
}
else{
System.out.println("null");
}
}catch(Exception e){
e.printStackTrace();
}
}
});
//-----------When user click on the listiview row-----------------------
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
timer.purge();
if(SessionText!=null&&IPText!=null){
try{
Intent i=new Intent(BaseActivity.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", sessionid);
i.putExtra("IPTEXT",iptext);
startActivity(i);
}catch(Exception e){
e.printStackTrace();
}
}
else{
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 5000);
}
}});
}
}
operatorDetail=null;
operatorList=null;
operatorDetail = result.split(delimiter1);
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
Button accept;
}
}
//------------------Play sound when user click on invite button-------------------------
private void playSound2() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.invite);
mp.start();
}
//---------------When any chat request come-----------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.chatinvitation);
mp.start();
}
//------------When user click on deny button---------------------
private void refuseToServer(String sessionid) {
// TODO Auto-generated method stub
//final String url = "http://sa.live2support.com/cpn/wz-action.php?";
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","refuse");
postParameters.put("csesid", sessionid);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Deny Chat response:"+response);
System.out.println("Deny chat Success"+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//---------------------When user click on invite button-----------------------
private void callToServer(String session) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","cinvt");
postParameters.put("csesid", session);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//------------------Show invitation alert----------------------
private void showAlert(String ip) {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "Invitation sent to "+ip;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();
}
//-----------------When in response we get the chat request--------------------------
private void chatRequest(String iptext, String sessionid) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ONCHATREQUEST;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("csesid", sessionid);
postParameters.put("ipaddr", iptext);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("join", "Y");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+response);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
public void onNotifiyDataSetChanged(){
super.notifyAll();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i=new Intent(BaseActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
what can i do for setting the row that has chat request on the top?Can anyone help me?
ArrayList<String> userList = your list of data
// other list also
//userListA
//userListB
ArrayList<String> tempUserList = new ArrayList<String>();
// other list also
//tempuserListA
//tempuserListB
String text = "ChatRequest";
// to add CharRequest at top
for(int i=0;i<userList.size();i++)
{
if(userList.get(i).equals(text))
{
tempUserList.add(userList.get(i));
//tempuserlistA.add(userlistA.get(i));
//tempuserlistB.add(userlistB.get(i));
}
}
// to add other entry
for(int i=0;i<userList.size();i++)
{
if(!userList.get(i).equals(text))
{
tempUserList.add(userList.get(i));
//tempuserlistA.add(userlistA.get(i));
//tempuserlistB.add(userlistB.get(i));
}
}
//now temp list are you original list to use
userList = tempUserList;
//userListA = tempuserlistA;
//userListB = tempuserlistB;
// and then call your adapter with the arraylists
You can use an ArrayList holding your Data for the ListView and add an item at the beginning of the list by: myArrayList.add(0, newItem).
Below an example Adapter which can do this:
public class PlaylistAdapter extends BaseAdapter {
private Context context;
private List<Playlist> entries;
public PlaylistAdapter(Context context, List<Playlist> entries) {
this.context = context;
this.entries = entries;
}
public void add(Playlist item) {
if (entries.contains(item))
return;
entries.add(item);
this.notifyDataSetChanged();
}
public void add(int index, Playlist item) {
if (entries.contains(item))
return;
entries.add(index, item);
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return entries.size();
}
#Override
public Playlist getItem(int arg0) {
return entries.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// inflate the layout you want to use for a single entry row
convertView = inflater.inflate(R.layout.playlists_adapter_entry,
null);
}
// fetches the current item
Playlist playlist = getItem(position);
// fill the entry layout with data
ImageView cover = (ImageView) convertView
.findViewById(R.id.playlist_adapter_entry_cover);
cover.setImageBitmap(playlist.getCover());
TextView title = (TextView) convertView
.findViewById(R.id.playlist_adapter_entry_title);
title.setText(playlist.getTitle());
return convertView;
}
}
I have a custom list view that is getting data from server and changing its content after each 3 seconds.this list view i am using for showing the visitor list who are visiting the site.Each row of list contains ipaddress,statustext,duration time,noofvisit and button text and data is updating and changing in list this part is working fine.
Actually i have an issue i have to the row on the top as first row of listview if status text is chat request.How can i do this?can anyone help me?
Actually i am using tabhost after login screen tabhost contains for tab one for monitoring window that show list of visitor and other are chat window,operatorlist and controls.
As i define above if i got status chat request then that row should appear on the top and will contains two button Accept and deny and on accept button click a window will open for chat and deny will use for refusing chat.
Can anyone help me for solving this issue?
my code is following
public class BaseActivity extends Activity {
private ListView list =null;
private NotificationManager mNotificationManager;
private final int NOTIFICATION_ID = 1010;
public static Timer timer = new Timer();
private String response;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText,StatusText;
private ArrayList<String> NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
private CustomAdapter adapter;
public static String from,sessionid,id,text,iptext,status,temo;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler;
public void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
try {
Log.i("UPDATE", "Handler called");
list.invalidateViews();
playSound3();
} catch(Exception e) {
Log.e("UPDATE ERROR", "error");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
//list.addView("chat request", 0);
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 7000);
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
logoutFromServer();
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private void playSound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_AllOnline;
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
//System.out.println("Output of httpResponse:"+response);
String result = response;
result = response;
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String[] temp = result.split(delimiter2);
operatorDetail = result.split(delimiter1);
if(temp.length==7){
String visitorString = temp[0];
String strSound = temp[3];
String strCSRmsgOrChatTrans = temp[4];
String stroperator = temp[5];
String strvisitor = temp[1];
visitorString = visitorString.trim();
if(!(visitorString.equals(""))||(visitorString.equalsIgnoreCase("No Visitors online")||(visitorString.equalsIgnoreCase("No Users Online")))){
operatorDetail = result.split(delimiter1);
//sizeoflist =operatorDetail.length;
}
else{
sizeoflist = 0;
}
}
else{
sizeoflist = operatorDetail.length;
}
//System.out.println("operatordetail length"+operatorDetail.length);
System.out.println("firstresponse================"+operatorDetail[0]);
if(operatorDetail[0].equalsIgnoreCase("logout")){
sizeoflist = 0;
System.exit(0);
finish();
}
if(temp[0].equalsIgnoreCase("No Users Online")){
if(temp[1].equalsIgnoreCase("0")){
sizeoflist =0;
}
else if(temp[1].length()>0){
sizeoflist = 0;
}
else if(temp[0].equalsIgnoreCase("")){
sizeoflist = 0;
}
sizeoflist =0;
}
else{
sizeoflist =operatorDetail.length;
}
//operatorDetail = result.split(delimiter1);
//--------Getting the size of the list---------------------
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
//playsound3();
noofchat =0;
list.setAdapter(new CustomAdapter(BaseActivity.this));
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setFastScrollEnabled(true);
//list.setSelected(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
});
}
else {
//ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//------------------------Getting the notification of no.of visitor on the site---------------------------
private void triggerNotification() {
// TODO Auto-generated method stub
CharSequence title = "No Of visitors";
CharSequence message = "New visit";
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, noofvisitors[0], System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, L2STest.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(BaseActivity.this, title, noofvisitors[0], pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
playsound4();
}
public void completed() {
//remove the notification from the status bar
mNotificationManager.cancel(NOTIFICATION_ID);
}
private void playsound4() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
//-----------------Logout from server--------------------
private void logoutFromServer() {
// TODO Auto-generated method stub
final String url ="http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_LOGOUT;
final HashMap<String, String> postParameters = new HashMap<String, String>();
try{
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
}catch(Exception e){
e.printStackTrace();
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// notificationManager.cancelAll();]
System.out.println(response);
showAlert1();
//getSharedPreferences(Main.PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
Log.e(DEB_TAG, response);
//System.exit(0);
Intent intent = new Intent(BaseActivity.this,Main.class);
startActivity(intent);
//closeHandler();
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//----------------------Logout alert when user click on logout button------------------
private void showAlert1() {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "You have Successfully logout.";
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.show();
}
//-------------------Play sound3 when any new user visit----------------
private void playsound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//------------------The adapter class------------------------------
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.notifyDataSetChanged();
SessionText.clear();
IPText.clear();
DurationText.clear();
StatusText.clear();
NoOfVisit.clear();
ButtonText.clear();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* #see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
//holder.accept = (Button) convertView.findViewById(R.id.btnaccept);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
holder.invite.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
for(int i=0;i<operatorDetail.length;i++){
if(operatorDetail!=null){
//System.out.println("Operator res=============="+operatorDetail[i]);
operatorList = operatorDetail[i].split(delimiter);
try{
if(operatorList[0]!=null){
SessionText.add(operatorList[0]);
sessionid = operatorList[0];
}
else{
onStart();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[1]!=null){
IPText.add(operatorList[1]);
iptext = operatorList[1];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[4]!=null){
DurationText.add(operatorList[4]);
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[3]!=null){
StatusText.add(operatorList[3]);
status = operatorList[3];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[2]!=null){
NoOfVisit.add(operatorList[2]);
}
else{
System.out.println("Oplst is null");
}
}catch(Exception e){
e.printStackTrace();
}
//ButtonText.add(operatorList[6]);
try{
if(IPText!=null){
holder.IP.setText(IPText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(DurationText!=null){
holder.duration.setText(DurationText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(StatusText!=null){
holder.status.setText(StatusText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(NoOfVisit!=null){
holder.noOfVisit.setText(NoOfVisit.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
//----------------If status is chat request then check for this-----------------
try{
if(StatusText.get(position).equalsIgnoreCase("chat request")){
//playsound();
playsound();
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.deny.setText("Deny");
convertView.bringToFront();
convertView.setFocusableInTouchMode(true);
convertView.setSelected(true);
//convertView.setFocusable(true);
convertView.requestFocus();
convertView.clearFocus();
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
try{
chatRequest(IPText.get(position), SessionText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
Intent i = new Intent(BaseActivity.this,Chat1.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
try{
i.putExtra("SessionText",SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
i.putExtra("StatusText",StatusText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
startActivity(i);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText!=null){
callToServer(SessionText.get(position));
}
else{
System.out.println("null");
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
catch(Exception e){
e.printStackTrace();
}
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText.get(position)!=null){
refuseToServer(SessionText.get(position));
holder.deny.setVisibility(View.INVISIBLE);
}
else{
System.out.println("null");
}
}catch(Exception e){
e.printStackTrace();
}
}
});
//-----------When user click on the listiview row-----------------------
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
timer.purge();
if(SessionText!=null&&IPText!=null){
try{
Intent i=new Intent(BaseActivity.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", sessionid);
i.putExtra("IPTEXT",iptext);
startActivity(i);
}catch(Exception e){
e.printStackTrace();
}
}
else{
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 5000);
}
}});
}
}
operatorDetail=null;
operatorList=null;
operatorDetail = result.split(delimiter1);
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
Button accept;
}
}
//------------------Play sound when user click on invite button-------------------------
private void playSound2() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.invite);
mp.start();
}
//---------------When any chat request come-----------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.chatinvitation);
mp.start();
}
//------------When user click on deny button---------------------
private void refuseToServer(String sessionid) {
// TODO Auto-generated method stub
//final String url = "http://sa.live2support.com/cpn/wz-action.php?";
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","refuse");
postParameters.put("csesid", sessionid);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Deny Chat response:"+response);
System.out.println("Deny chat Success"+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//---------------------When user click on invite button-----------------------
private void callToServer(String session) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","cinvt");
postParameters.put("csesid", session);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//------------------Show invitation alert----------------------
private void showAlert(String ip) {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "Invitation sent to "+ip;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();
}
//-----------------When in response we get the chat request--------------------------
private void chatRequest(String iptext, String sessionid) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ONCHATREQUEST;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("csesid", sessionid);
postParameters.put("ipaddr", iptext);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("join", "Y");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+response);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
public void onNotifiyDataSetChanged(){
super.notifyAll();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i=new Intent(BaseActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
what can i do for setting the row that has chat request on the top?Can anyone help me?
Create you customListItem with visibility set to View.GONE by default. When you have a chat request, then just change its visibility to View.VISIBLE and refresh your list. Simple.
If you want to add some view as the first row of your listview, then use
listview.addHeaderView(myHeaderView);
use this before setting list adapter.
try like this..
boolean bool=true;
new Thread(new Runnable() {
public void run() {
while(bool){
int t=StatusText.IndexOf(chat)
if(t!=-1)
{
Collections.swap(StatusText,0,t);
Collections.swap(SessionText,0,t);
Collections.swap(IPText,0,t);
Collections.swap(DurationText,0,t);
Collections.swap( NoOfVisit ,0,t);
Collections.swap(ButtonText,0,t);
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});