Loading Progress Bar android - android

*I have class which load some files and update the UI...It takes some times to view the result,... So I want to add a loading bar or progress bar. Some data has been passed by other activity(Bundle extras1 = getIntent().getExtras();). But I am downloading one image per item... I think that takes more time. Any one can help me?
This is my code:
public class ShowSelectedEvents extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewdetailsevents);
Bundle extras1 = getIntent().getExtras();
String eventTitle = extras1.getString("eventTitle");
final String address = extras1.getString("address");
String date = extras1.getString("date");
String time = extras1.getString("time");
final String fix = extras1.getString("fix");
final String mobile = extras1.getString("mobile");
final String web = extras1.getString("web");
final String mail = extras1.getString("mail");
String imageLink = extras1.getString("imageLink");
final String videoLink = extras1.getString("videoLink");
// Add item image
Bitmap bitMap = null;
try {
bitMap = DownloadImage("imageLink);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView imageItem = (ImageView) findViewById(R.id.imageItem);
imageItem.setImageBitmap(bitMap);
TextView viewTitle = (TextView) findViewById(R.id.viewTitle);
viewTitle.setText(eventTitle);
TextView viewDateTime = (TextView) findViewById(R.id.dateTime);
viewDateTime.setText("Event is on "+date +" # "+ time);
// View Address
TextView viewAdd = (TextView) findViewById(R.id.viewAddress);
viewAdd.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewAdd.setText(address);
// On click open Navigation
if (!(address.equals("-"))){
ImageView navigationIcon = (ImageView) findViewById(R.id.imageMapNavigation);
navigationIcon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "google.navigation:q="+address;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Address is incomplete!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// View Phone number
TextView viewPhoneNumber = (TextView) findViewById(R.id.viewPhoneNumber);
viewPhoneNumber.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewPhoneNumber.setText(fix);
// On click open call
if (!(fix.equals("-"))){
viewPhoneNumber.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "tel:"+fix;
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(i);
}
});
}
//View Mobile number
TextView viewMobileNumber = (TextView) findViewById(R.id.viewMobileNumber);
viewMobileNumber.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewMobileNumber.setText(mobile);
// on click call mobile number
if (!(mobile.equals("-"))){
viewMobileNumber.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "tel:"+mobile;
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(i);
}
});
}
//View web url
TextView viewWeb = (TextView) findViewById(R.id.viewWeb);
viewWeb.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewWeb.setText(web);
//on click open web browser
if (!(web.equals("-"))){
viewWeb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(web));
startActivity(i);
}
});
}
TextView viewMail = (TextView) findViewById(R.id.viewMailAddress);
viewMail.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewMail.setText(mail);
if(!(mail.equals("-"))){
viewMail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {mail});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contact from tamilpage.ch");
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Send a mail ..."));
}
});
}
// On click play the video
if (!(address.equals("-"))){
ImageView videoIcon = (ImageView) findViewById(R.id.videoButton);
videoIcon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(videoLink));
startActivity(browserIntent);
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "No advert video for this event";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
private Bitmap DownloadImage(String url) throws Exception {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String url) throws Exception {
InputStream in = null;
int response = -1;
System.out.println("Nishi1");
URL url1 = new URL(url);
URLConnection conn = url1.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
System.out.println(in);
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}

So I want to add a loading bar or progress bar
For your approach you need to use Threads. Especially i recommend to you have look at
Handler
AsyncTask
Both approaches offer work with Threads. AsyncTask is more complex than Handler also it's generic-type so offer more type-safe and faster work.
You should read some tutorials so
ProgressBar updating using Message Handler
Create A Custom Progress Bar Using
AsyncTask
And there is very awesome and useful tutorial at Vogella
Android Threads, Handlers and AsyncTask -
Tutorial

I would look at using AsyncTask. Here is a link that should help you get started: http://developer.android.com/reference/android/os/AsyncTask.html

The way you're going to want to do this is within an ASyncTask that has callbacks for updating a progress bar. I've included a sample below that doesn't actually do anything. You'd put your code for calling the download in doInBackground() and update the progress from onProgressUpdate.
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPostExecute", Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}

Related

Value passed from one Actvity to another arrives as Null in Android

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");

Sharing Image and Text On twitter not working

This is my code given below.FrameLayout is Used to share as JPEG Image on twitter.This is the code Im trying .
sharesp=(Spinner)findViewById(R.id.spnrShare);
sharesp.setAdapter(new MyShAdapter(MainActivity.this, R.layout.rowview, Sharestring));
sharesp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
selectitem=parent.getItemAtPosition(position).toString();
selecetint=position;
if(selectitem=="FaceBook" || selecetint==R.drawable.fbbtn){
shareFbook();
}
else if(selectitem=="Twitter" || selecetint==R.drawable.twitbtn){
shareTwitter();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public void shareTwitter(){
FrameLayout savFrame_layout=(FrameLayout)findViewById(R.id.frame);
try {
if(MainActivity.this.mainFrame_layout==null){
MainActivity.this.mainFrame_layout.setDrawingCacheEnabled(true);
MainActivity.this.mainFrame_layout.refreshDrawableState();
MainActivity.this.mainFrame_layout.buildDrawingCache();
MainActivity.this.bm_ImgFrame = mainFrame_layout.getDrawingCache();
int i1=100000;
Random random=new Random();
i1=random.nextInt(i1);
MainActivity.fname = "Quick_"+ i1 + ".jpg";
String pathy=Environment.getExternalStorageDirectory()+File.separator+"/MYAnApps";
MainActivity.this.rootFile=new File(pathy);
MainActivity.this.sdImageMainDirectory = new File(MainActivity.this.rootFile + MainActivity.fname);
FileOutputStream fileOutputStream = new FileOutputStream(MainActivity.this.sdImageMainDirectory);
bm_ImgFrame.compress(CompressFormat.JPEG, 80, fileOutputStream);
Uri uri = Uri.parse(MainActivity.this.sdImageMainDirectory.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("/*");
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
intent.putExtra(Intent.EXTRA_TEXT, "MyAndroidApp: https://play.google.com/store/apps/details?id=com.example.MyApp");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(MainActivity.this.sdImageMainDirectory));
startActivity(intent);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try using "*/*" as MIME, so you can send any generic data type.
intent.setType("*/*");
Also try changing ACTION_SEND to ACTION_SEND_MULTIPLE which specialized for delivering multiple data.
More info about ACTION_SEND_MULTPLE and handling MIME types.
Check this Example this is working for me
Twitter Image And text sharing Example
twitter sharing using this one
private void showTwittDialog() {
final Dialog dialog = new Dialog(getApplicationContext());
dialog.setContentView(R.layout.twitt_dialog);
dialog.setTitle("Twitter");
Button btnPost = (Button) dialog.findViewById(R.id.btnpost);
final EditText et = (EditText) dialog.findViewById(R.id.twittext);
et.setText(sharingStr);
et.setSelection(et.getText().length());
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
twitt_msg = et.getText().toString().trim();
if (twitt_msg.length() == 0) {
showToast("Tweet is empty!!!");
return;
} else if (twitt_msg.length() > 140) {
showToast("Tweet of more than 140 characters not allowed!!!");
return;
}
dialog.dismiss();
new PostTwittTask().execute(twitt_msg);
}
});
dialog.show();
}
protected void Share_to_twitter() {
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
tweetIntent.putExtra(Intent.EXTRA_TEXT, sharingStr);
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : list) {
twitter_dialog = resolveInfo.activityInfo.packageName;
}
if (twitter_dialog != null && twitter_dialog.startsWith("com.twitter.android")) {
// if the native twitter app is found
tweetIntent.setPackage(twitter_dialog);
startActivity(tweetIntent);
} else {
showTwittDialog();
}
mTwitter.resetAccessToken();
}
class PostTwittTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Posting Twitt...");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... twitt) {
try {
mTwitter.updateStatus(twitt[0]);
return "success";
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
return "Posting Failed because of Duplicate message...";
}
e.printStackTrace();
return "Posting Failed!!!";
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (null != result && result.equals("success")) {
View popUpView = getLayoutInflater().inflate(R.layout.share_successfully_popup,null);
final PopupWindow popUp = new PopupWindow(popUpView,UtilityClass.dynamicScalingForWidth(100),
UtilityClass.dynamicScalingForWidth(100),true);
popUp.showAtLocation(popUpView.findViewById(R.id.share_successfully_ctr),Gravity.CENTER,0, 0);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
popUp.dismiss();
}
};
handler.postDelayed(r, 3000);
} else {
showToast(result);
}
super.onPostExecute(result);
}
}

Set time for Custom Dialog

When the user clik on Register Button, a Custom Dialog box appear and the user move to the menu. But in my case, the Costum Dialog appear just for one second and then the user pass to the next layout.
How to set a time for the Custom Dialog please ?
Here my code :
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
final String name = inputName.getText().toString();
final String mail = inputEmail.getText().toString();
final String password = inputPassword.getText()
.toString();
PatientFunctions patientFunction = new PatientFunctions();
json = patientFunction.registerPatient(name, mail,
password);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
Intent main = new Intent(
getApplicationContext(), Main.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
finish();
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
CustomizeDialog customizeDialog = new CustomizeDialog(RegisterPatient.this);
customizeDialog.show();
Handler handler = null;
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
customizeDialog.cancel();
customizeDialog.dismiss();
}
}, 3000);
}
});
There are many good options including AlarmManager, Timer & TimerTask
You can use a handler too like so:
Handler handler = null;
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
customdialog.cancel();
customdialog.dismiss();
}
}, 500);
the best way to do these kind of process is to use AsyncTask class
and override onPreExecute and doInBackground and onPostExecute
see the official guide
implement the doInBackground() callback method, which runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by calling execute() from the UI thread
private class Registration extends AsyncTask<String, Void, String>{
CustomizeDialog customizeDialog;
#Override
protected void onPreExecute() {
// show ur dialog
customizeDialog = new CustomizeDialog(RegisterPatient.this);
customizeDialog.show();
}
#Override
protected String doInBackground(String... params) {
final String name = params[0];
final String email = params[1];
final String password = params[2];
PatientFunctions patientFunction = new PatientFunctions();
json = patientFunction.registerPatient(name, mail,
password);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
return res;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
if (Integer.parseInt(res) == 1) {
if(customizeDialog != null)
customizeDialog.dismiss();
Intent main = new Intent(
getApplicationContext(), Main.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//move to the next activity
startActivity(main);
finish();
}
}
}
Edit
and then execute it what ever you want
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String name = inputName.getText().toString();
final String mail = inputEmail.getText().toString();
final String password = inputPassword.getText()
.toString();
new Registration().execute(name,mail,password);
}
});

Apply html tags to textview in android

I am displaying data from sqlite db. The data in the database is stored in html. The data contains an image tag to display an image. I am able to display the data but how can I display the image along with it? My images are stored in the server.
My Code:
((TextView)view.findViewById(R.id.tv_text)).setText(Html.fromHtml(listItem.gettext()+""));
From the above line I am displaying the data from database. Now along with that I need to display the image which is in server. How can I do this?
Try my code . Hope it helps
TextView mDetail;
ProgressBar mProgressBar;
String body;
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_recipe_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (this.getIntent().getStringExtra("body") != null)
body = this.getIntent().getStringExtra("body");
mDetail = (TextView) this.findViewById(R.id.tv_recipe_detail);
if (this.getIntent().getStringExtra("body") != null)
body = this.getIntent().getStringExtra("body");
mDetail.setText(Html.fromHtml(body));
mProgressBar = (ProgressBar) this.findViewById(R.id.bar);
mDetail.setMovementMethod(ScrollingMovementMethod.getInstance());// 皛
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 0x101) {
mProgressBar.setVisibility(View.GONE);
mDetail.setText((CharSequence) msg.obj);
}
super.handleMessage(msg);
}
};
Thread t = new Thread(new ImageTask());
t.start();
mProgressBar.setVisibility(View.VISIBLE);
}
class ImageTask implements Runnable {
Message msg = Message.obtain();
#Override
public void run() {
ImageGetter imageGetter = new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
URL url;
Drawable drawable = null;
try {
url = new URL(source);
drawable = Drawable.createFromStream(
url.openStream(), null);
int scale_y = MAX_HEIGHT/drawable.getIntrinsicHeight();
drawable.setBounds(0, 0,
drawable.getIntrinsicWidth()*scale_y,
drawable.getIntrinsicHeight()*scale_y);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException" + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException" + e.toString());
}
return drawable;
}
};
CharSequence test = Html.fromHtml(body, imageGetter, null);
msg.what = 0x101;
msg.obj = test;
handler.sendMessage(msg);
}
}

How to add list view row on the top if list view has dynamic data getting from server in android [closed]

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;
}
}

Categories

Resources