Activity not opening on button press - android

I am creating a basic android application with a client - server chat, a link to a website and on option to open a database (that I am yet to create). I have created a button to open the activity for the database but nothing happens when I press the button.
Here is my application main activity;
public class AndroidChatApplicationActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
// msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
Button websiteButton = (Button) findViewById(R.id.website_Button);
websiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendToWebsite();
}
});
}
protected void sendToWebsite() {
String url = "https://www.ljmu.ac.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Button databaseButton = (Button) findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AndroidChatApplicationActivity.this,
Database.class));
}
});
}
// receiveMsg();
// ----------------------------
// server msg receieve
// -----------------------
// End Receive msg from server//
public void sendMessageToServer(String str) {
final String str1 = str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// String host = "opuntia.cs.utep.edu";
String host = "10.0.2.2";
String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
// out.println("hello");
out.println(str1);
Log.d("", "test");
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test3");
}
}
}).start();
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// final String host="opuntia.cs.utep.edu";
final String host = "10.0.2.2";
// final String host="localhost";
Socket socket = null;
BufferedReader in = null;
try {
socket = new Socket(host, 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
Log.d("", "MSGGG: " + msg);
// msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("", "Hi Test");
}
});
}
}
Here is my manifest;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.UTEP.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:allowTaskReparenting="false"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name="androidChat.AndroidChatApplicationActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="androidChat.Database" >
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
And here is database as it stands;
import android.app.Activity;
import android.os.Bundle;
import edu.UTEP.android.R;
public class Database extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
}
}

As you said that "nothing happens", I'm assuming your button clickListener isn't even get called. Try moving this to your OnCreate method:
Button databaseButton = (Button) findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AndroidChatApplicationActivity.this,
Database.class));
}
});

Related

Crash when starting activity

i am coding an android app. The app begins at the main screen then click the button to go the activity. My code does not have any error and build fine. However launching the app and click the button result in a crash.
My Manifest.XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidbtcontrol">
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".bluetoothconnect">
<intent-filter>
<action android:name="com.example.androidbtcontrol.bluetoothconnect" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
public void OnclickButtonListener(){
button_1 = (Button)findViewById(R.id.button);
button_1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.androidbtcontrol.bluetoothconnect");
startActivity(intent);
}
}
);
}
}
bluetoothconnect.java
public class bluetoothconnect extends AppCompatActivity {
protected void onCreate3(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetoothconnect);
}
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter bluetoothAdapter;
ArrayList<BluetoothDevice> pairedDeviceArrayList;
TextView textInfo, textStatus;
ListView listViewPairedDevice;
RelativeLayout inputPane;
SeekBar barAnalogOut;
ArrayAdapter<BluetoothDevice> pairedDeviceAdapter;
private UUID myUUID;
private final String UUID_STRING_WELL_KNOWN_SPP =
"00001101-0000-1000-8000-00805F9B34FB";
ThreadConnectBTdevice myThreadConnectBTdevice;
ThreadConnected myThreadConnected;
protected void onCreate2(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textInfo = (TextView)findViewById(R.id.info);
textStatus = (TextView)findViewById(R.id.status);
listViewPairedDevice = (ListView)findViewById(R.id.pairedlist);
inputPane = (RelativeLayout) findViewById(R.id.inputpane);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(this,
"FEATURE_BLUETOOTH NOT support",
Toast.LENGTH_LONG).show();
finish();
return;
}
//using the well-known SPP UUID
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this,
"Bluetooth is not supported on this hardware platform",
Toast.LENGTH_LONG).show();
finish();
return;
}
String stInfo = bluetoothAdapter.getName() + "\n" +
bluetoothAdapter.getAddress();
textInfo.setText(stInfo);
barAnalogOut = (SeekBar)findViewById(R.id.analogOut);
barAnalogOut.setOnSeekBarChangeListener(OnAnalogOutChangeListener);
}
SeekBar.OnSeekBarChangeListener OnAnalogOutChangeListener =
new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//will generate too much data sent!
//SendAnalogOut(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
SendAnalogOut(seekBar.getProgress());
}
};
private final byte SYNC_BYTE = (byte) 0xAA;
private final byte LENGTH_ANALOG = (byte) 3;
private final byte CMD_ANALOG = (byte) 1;
private void SendAnalogOut(int val){
byte[] bytesToSend = {SYNC_BYTE, LENGTH_ANALOG, CMD_ANALOG, (byte) val};
myThreadConnected.write(bytesToSend);
}
#Override
protected void onStart() {
super.onStart();
//Turn ON BlueTooth if it is OFF
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
setup();
}
private void setup() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
pairedDeviceArrayList = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
pairedDeviceArrayList.add(device);
}
pairedDeviceAdapter = new ArrayAdapter<BluetoothDevice>(this,
android.R.layout.simple_list_item_1, pairedDeviceArrayList);
listViewPairedDevice.setAdapter(pairedDeviceAdapter);
listViewPairedDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
BluetoothDevice device =
(BluetoothDevice) parent.getItemAtPosition(position);
Toast.makeText(bluetoothconnect.this,
"Name: " + device.getName() + "\n"
+ "Address: " + device.getAddress() + "\n"
+ "BondState: " + device.getBondState() + "\n"
+ "BluetoothClass: " + device.getBluetoothClass() + "\n"
+ "Class: " + device.getClass(),
Toast.LENGTH_LONG).show();
textStatus.setText("start ThreadConnectBTdevice");
myThreadConnectBTdevice = new ThreadConnectBTdevice(device);
myThreadConnectBTdevice.start();
}
});
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(myThreadConnectBTdevice!=null){
myThreadConnectBTdevice.cancel();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_ENABLE_BT){
if(resultCode == Activity.RESULT_OK){
setup();
}else{
Toast.makeText(this,
"BlueTooth NOT enabled",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
//Called in ThreadConnectBTdevice once connect successed
//to start ThreadConnected
private void startThreadConnected(BluetoothSocket socket){
myThreadConnected = new ThreadConnected(socket);
myThreadConnected.start();
}
/*
ThreadConnectBTdevice:
Background Thread to handle BlueTooth connecting
*/
private class ThreadConnectBTdevice extends Thread {
private BluetoothSocket bluetoothSocket = null;
private final BluetoothDevice bluetoothDevice;
private ThreadConnectBTdevice(BluetoothDevice device) {
bluetoothDevice = device;
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);
textStatus.setText("bluetoothSocket: \n" + bluetoothSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SendAnalogOut( 0);
// The toggle is enabled
} else {
SendAnalogOut( 255);
// The toggle is disabled
}
}
});
boolean success = false;
try {
bluetoothSocket.connect();
success = true;
} catch (IOException e) {
e.printStackTrace();
final String eMessage = e.getMessage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textStatus.setText("Something wrong BluetoothSocket.connect(): \n" + eMessage);
}
});
try {
bluetoothSocket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(success){
//connect successful
final String msgconnected = "Connect Successful:\n"
+ "BluetoothSocket: " + bluetoothSocket + "\n"
+ "BluetoothDevice: " + bluetoothDevice;
runOnUiThread(new Runnable(){
#Override
public void run() {
textStatus.setText(msgconnected);
listViewPairedDevice.setVisibility(View.GONE);
inputPane.setVisibility(View.VISIBLE);
}});
startThreadConnected(bluetoothSocket);
}else{
//fail
}
}
public void cancel() {
Toast.makeText(getApplicationContext(),
"close bluetoothSocket",
Toast.LENGTH_LONG).show();
try {
bluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
ThreadConnected:
Background Thread to handle Bluetooth data communication
after connected
*/
private class ThreadConnected extends Thread {
private final BluetoothSocket connectedBluetoothSocket;
private final InputStream connectedInputStream;
private final OutputStream connectedOutputStream;
public ThreadConnected(BluetoothSocket socket) {
connectedBluetoothSocket = socket;
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectedInputStream = in;
connectedOutputStream = out;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = connectedInputStream.read(buffer);
String strReceived = new String(buffer, 0, bytes);
final String msgReceived = String.valueOf(bytes) +
" bytes received:\n"
+ strReceived;
runOnUiThread(new Runnable() {
#Override
public void run() {
textStatus.setText(msgReceived);
}});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String msgConnectionLost = "Connection lost:\n"
+ e.getMessage();
runOnUiThread(new Runnable(){
#Override
public void run() {
textStatus.setText(msgConnectionLost);
}});
}
}
}
public void write(byte[] buffer) {
try {
connectedOutputStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void cancel() {
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Main Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="Please Choose "
android:textStyle="bold" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button" />
</LinearLayout>
Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_bluetoothconnect"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidbtcontrol.bluetoothconnect">
<TextView
android:id="#+id/info"
android:textStyle="bold|italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/pairedlist"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/inputpane"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
</RelativeLayout>
<SeekBar
android:id="#+id/analogOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="99"
android:progress="0"/>
<ToggleButton
android:text="ToggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toggleButton" />
</RelativeLayout>
These are some of the mistakes I can spot from the information you have given. Post the logcat exception details so that I can refine on this solution.
1) Don't use your own version of onCreate (in bluetoothactivity). An activity should have only one onCreate method. You also need to add the #Override prefix to the onCreate method. The code you have contains onCreate2 and onCreate3 methods which are erroneous. That may be the reason for the crash, since when the bluetooth activity is called, it can't find the onCreate method.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Keep your bluetooth related functionality here.
}
2) When launching your intent, you need to specify the source and the destination too.
Intent intent = new Intent(CallingActivity.this,CalledActivity.class);
startActivity(intent);
Your crash maybe caused due to your intent,in activity
Intent intent = new Intent("com.example.androidbtcontrol.bluetoothconnect");
startActivity(intent);
the right way
Intent intent=new Intent(firstactivity.this,secondactivity.class);
startactivity(intent);
you need to specify the destination

set fetched data from database to a textview after calling intent

I've created a Textview with a null value and button in my my Mainactivity and fetched some data from sql database server using AsyncTask method on button click and stored in to my textview. Then I called an intent to another activity activity2 to show something and I returned to my Mainactivity using intent.But I can't view the previously set data in textview. It shows null value.I want to set it previously fetched data.how can I set that?
public class MainActivity extends Activity {
public ImageView prev, now, next;
String depvisitid;
public TextView display, bottom, ptname, docname;
public String tokenh,tokenext,tokennow;
public String pname,pnamenext,pnamenow;
public boolean status;
public String drname,current;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (ImageView) findViewById(R.id.previmg);
now = (ImageView) findViewById(R.id.token);
next = (ImageView) findViewById(R.id.nextimg);
display = (TextView) findViewById(R.id.textView2);
ptname = (TextView) findViewById(R.id.textView3);
bottom = (TextView) findViewById(R.id.tokennum);
docname = (TextView) findViewById(R.id.textView);
// Connect runner = new Connect();
// runner.execute();
The setOnClickListener method:
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String sleepTime = time.getText().toString();
}
});
now.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
display.setText(tokenh);
ConnectNow nw = new ConnectNow();
nw.execute();
Intent i = new Intent(getApplicationContext(), StatusUpdate.class);
i.putExtra("patientname", pname);
i.putExtra("tokenno", tokenh);
i.putExtra("depvisitid", depvisitid);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connect runner = new Connect();
runner.execute();
}
});
}
The onBackPressed:
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
// finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
class Connect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet reset1 = null;
try {
reset1 = stmt.executeQuery(" select a.TOKENNO,b.FNAME,a.TOKENSTATUS,e.EMPFNAME,a.DEPVISITID from DEPTVISIT a,PATIENT_MASTER b,APP_EMPLOYEE e where a.PID=b.PID and (a.TOKENSTATUS='O' or a.TOKENSTATUS='S' ) and e.EMPID=a.EMPID and a.EMPID=2 and CONVERT(date,a.OPDATE)='2016-05-09' order by TOKENNO desc;");
while (reset1.next()) {
tokenh = reset1.getString("TOKENNO");
pname = reset1.getString("FNAME");
drname = reset1.getString("EMPFNAME");
depvisitid= reset1.getString("DEPVISITID");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return tokenh;
}
protected void onPostExecute(String result) {
bottom.setText(tokenh);
ptname.setText(pname);
docname.setText(drname);
}
}
The connect now class:
class ConnectNow extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "ssssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj****");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open****");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='S' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
System.out.println("status updated to S");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return status;
}
protected void onPostExecute(Boolean result) {
bottom.setText(tokenh);
ptname.setText(pnamenext);
docname.setText(drname);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings=new Intent(getApplicationContext(),Settings.class);
startActivity(settings);
}
return super.onOptionsItemSelected(item);
}
}
SECOND ACTIVITY StatusUdate.java:
public class StatusUpdate extends Activity {
public String tokenstatN, tokenstatY;
Button visited, notvisited;
String pname,tokennum,depvisitid;
TextView patnam,tknum;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statusupdate);
visited = (Button) findViewById(R.id.button);
notvisited = (Button) findViewById(R.id.button2);
patnam= (TextView) findViewById(R.id.textView4);
tknum= (TextView) findViewById(R.id.textView5);
Bundle extras = getIntent().getExtras();
pname = extras.getString("patientname");
tokennum = extras.getString("tokenno");
depvisitid = extras.getString("depvisitid");
patnam.setText(pname);
tknum.setText(tokennum);
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
The NotVisit class:
class NotVisit extends AsyncTask<String, String, Boolean> {
boolean status = false;
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openhhhh");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "openlll");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='N' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.d("status", String.valueOf(status));
return status;
}
}
Whenever you wish to go to previous screen, Always finish the Activity that is on top. Here in your case, You are always creating new instance of MainActivity and this is the reason for getting null when you go back. Try using this in your StatusUpdate.java.
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
StatusUpdate.this.finish();
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
StatusUpdate.this.finish();
}
});
You can store the retrieved text in a static field of your activity class, but it's better save and restore it on activity recreation.So modify your activity like:
#Override
public void onCreate(Bundle b) {
// activity initialization
// textView = ...
if (b != null) {
textView.setText(b.getString("dbtext"));
}
}
and
#Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
b.putString("dbtext", textView.getText());
}

passing data from BroadcastReceiver to class that extends runnable

My goal is to create a method that gets the data from broadcast receiver and sends it trough a socket. I know how to send it, but how can i get a data from BroadcastReceiver ? I want to receive data in this class:
public class ClientThread implements Runnable{
Socket socket;
public final String TAG = "CLIENT";
ObjectOutputStream os;
TextView text;
Handler handler;
AppHelper helperClass;
Activity mActivity;
Context mContext;
public ClientThread(Activity mActivity,TextView text,Context context) {
// TODO Auto-generated constructor stub
this.text=text;
this.mContext=context;;
helperClass = new AppHelper(context, mActivity);
handler = new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket
.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
String line = null;
while ((line = in.readUTF().toString()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
if (mesg.contains("getcontacts")) {
try {
sendContacts();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (mesg.contains("getmsg")) {
getMessages();
} else if (mesg.contains("sendmsg")) {
sendMessage(mesg);
} else {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
public void receivedMessage(String sender, String message) {
}
private void sendMessage(String s) {
String[] x = s.split(" ");
int lenght = x.length;
String message = x[2];
for (int i = 3; i < x.length; i++) {
message = message + " " + x[i];
}
System.out.println(message);
SmsManager smsManager = SmsManager.getDefault();
System.out.println("sending message");
smsManager.sendTextMessage(x[1], null, message, null, null);
System.out.println("message send");
}
private void sendContacts() throws IOException {
final List<Person> list = helperClass.getContacts();
final String json = new Gson().toJson(list);
Log.i(TAG, "lenght " + json.length());
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
os.writeObject(json);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Sending Contact list has failed");
e.printStackTrace();
}
}
});
}
private void getMessages() {
// TODO Auto-generated method stub
ProgressTask task = new ProgressTask();
ProgressTask.execute(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<Sms> sms = helperClass.getAllSms();
final String json = new Gson().toJson(sms);
os.writeObject(json);
os.flush();
System.out.println("List of messages send");
} catch (Exception e) {
Log.e(TAG, "Sending Contact list has failed");
}
}
});
}
}
You may use an interface as listener to this runnable.
Create a Listener interface
Declare Interface Variable in Application Context.
Instantiate and implement interface in Runnable class.
In BroadcastReciever, call method of that interface.
Ex:
Class A extends Application{
public Listener listener;
}`
interface Listener{
public void yourmethod();
}
In Your clientthread method instantiate listener as follows:
((A)context.getApplication()).listener = new Listener(){
#override
public void yourmethod(){
// your implementation goes here
}
}
In your broadcast reciever.
((A)context.getApplication()).listener.yourmethod();

Application close when rotate main (Activity ) screen in android

I am making two layout one is for Landscape and another is for portrait.
And make layout-land folder for Landscape and put all landscape layout, All Landscape Layout is working fine but when i rotate on Main Activity then It,s close.
removed layout-land folder and tried then again close the App
Main Activity
<activity
android:name=".UnsignPropertyAlert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
UnsignPropertyAlert class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unsignalert);
Commons.setContext(context);
listView =(ListView) findViewById(R.id.list);
// listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
btnregister= (TextView) findViewById(R.id.login);
btnNext= (Button) findViewById(R.id.btnnext);
btnPrev= (Button) findViewById(R.id.btnprev);
AdView adView = (AdView)this.findViewById(R.id.adView);
//adView.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
Bundle bundle = new Bundle();
bundle.putString("color_bg","#fdfbfc");
bundle.putString("color_text", "#81BE32");
AdMobExtras extras = new AdMobExtras(bundle);
adRequest = new AdRequest.Builder()
.addNetworkExtras(extras)
.build();
// btnNext.setVisibility(View.INVISIBLE);
// btnPrev.setVisibility(View.INVISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
nextProp();
}
});
btnPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
prevProp();
}
});
login = new File("/data/data/com.dwellesque/shared_prefs/Login.xml");
if(Commons.HaveNetworkConnection(context))
{
if(login.exists())
{
btnregister.setText("LOGIN");
preferences=getSharedPreferences("Login", MODE_PRIVATE);
String zip= preferences.getString("ZIP", "");
url="http://www.......";
backurl="http://www.....";
}
else
{
url="http://www......";
backurl="http://www.......";
}
pd=new ProgressDialog(UnsignPropertyAlert.this,ProgressDialog.THEME_HOLO_LIGHT);
pd.setMessage("Loading....");
pd.setTitle(null);
pd.show();
url=url.replace(" ", "%20");
Log.d("First", url);
JsonRequestAsycn task=new JsonRequestAsycn();
task.execute(url);
task.delegate=UnsignPropertyAlert.this;
}
else
{
Toast.makeText(context, "Please check your internet connection! ", Toast.LENGTH_LONG).show();
}
btnSearch= (TextView) findViewById(R.id.search);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(UnsignPropertyAlert.this,Main_Serach.class));
}
});
btnregister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(btnregister.getText().toString().equals("LOGIN"))
{
startActivity(new Intent(UnsignPropertyAlert.this,Login.class));
}
else
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www......."));
startActivity(browserIntent);
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String url = arlisturl.get(position);
Log.d("URL", url);
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
listView.setOnTouchListener(new OnSwipeTouchListener(context) {
#Override
public void onSwipeLeft() {
// Whatever
nextProp();
// Toast.makeText(context, "left", Toast.LENGTH_LONG).show();
}
public void onSwipeRight() {
// Whatever
prevProp();
// Toast.makeText(context, "Right", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void processFinish(String output) {
pd.dismiss();
// TODO Auto-generated method stub
if(output.trim().contains("Result not found !") || output.length()==114 || output.length()<1)
{
Toast.makeText(context, "Property Not Found", Toast.LENGTH_LONG).show();
}
else if(output.trim().contains("TimeOut"))
{
Toast.makeText(context, "Connection Timeout!", Toast.LENGTH_LONG).show();
}
else
{
showdata(output,listView,true);
}
}
// Set Data in List View
void showdata(String data,ListView lv,Boolean first)
{
doc = XMLfunctions.XMLfromString(data);
NodeList nodes = doc.getElementsByTagName("PROPERTY");
for (int i = 0; i<nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
// Street Name
if (!("null").equals(XMLfunctions.getValue(e, "street"))) {
arliststitname.add(XMLfunctions.getValue(e, "street"));
} else {
arliststitname.add(" ");
}
// Location
if (!("null").equals(XMLfunctions.getValue(e, "city"))) {
if(!("null").equals(XMLfunctions.getValue(e, "state")))
{
arlistlocation.add(XMLfunctions.getValue(e, "city")+" ,"+XMLfunctions.getValue(e, "state"));
}
arlistlocation.add(XMLfunctions.getValue(e, "city"));
} else {
arlistlocation.add(" ");
}
// Square Footage
if (!("null").equals(XMLfunctions.getValue(e, "SquareFootage"))) {
arlistsqare.add(XMLfunctions.getValue(e, "SquareFootage"));
} else {
arlistsqare.add(" ");
}
// price
if (!("null").equals(XMLfunctions.getValue(e, "price"))) {
arlistprice.add(XMLfunctions.getValue(e, "price"));
} else {
arlistprice.add(" ");
}
// Images
if (!("null").equals(XMLfunctions.getValue(e, "picture"))) {
String[] imageUrls=XMLfunctions.getValue(e, "picture").split("\\|\\|");
arlistimg.add(imageUrls[0]);
} else {
arlistimg.add("");
}
// posted on
if (!("null").equals(XMLfunctions.getValue(e, "EnteredDate"))) {
arlistposted.add(XMLfunctions.getValue(e, "EnteredDate"));
} else {
arlistposted.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "description"))) {
arlistDesc.add(XMLfunctions.getValue(e, "description"));
} else {
arlistDesc.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "propertystatus"))) {
arlistproperty.add(XMLfunctions.getValue(e, "propertystatus"));
} else {
arlistproperty.add("");
}
if (!("null").equals(XMLfunctions.getValue(e, "EnteredDate"))) {
arlistyear.add(XMLfunctions.getValue(e, "EnteredDate"));
} else {
arlistyear.add("");
}
//URL
if (!("null").equals(XMLfunctions.getValue(e, "propertyurl"))) {
arlisturl.add(XMLfunctions.getValue(e, "propertyurl"));
} else {
arlisturl.add("");
}
// ID
if (!("null").equals(XMLfunctions.getValue(e, "id"))) {
arlistID.add(XMLfunctions.getValue(e, "id"));
} else {
arlistID.add("");
}
}
if(first)
{
lv.setAdapter(null);
String[] Street={ arliststitname.get(0) };
adapter= new
AlertListAdapter(context,arlistimg.get(0), Street, arlistlocation.get(0),
arlistsqare.get(0), arlistprice.get(0),arlistposted.get(0),arlisturl.get(0),arlistID.get(0));
lv.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(login.exists())
{
btnregister.setText("LOGIN");
}
}
#Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
else
return true;
}
}
return false;
}
#Override
public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
void nextProp()
{
if(Commons.HaveNetworkConnection(context))
{
if(proppos<arliststitname.size()-2)
{
btnPrev.setEnabled(true);
proppos++;
listView.setAdapter(null);
String[] Street={ arliststitname.get(proppos) };
adapter= new
AlertListAdapter(context,arlistimg.get(proppos), Street, arlistlocation.get(proppos),
arlistsqare.get(proppos), arlistprice.get(proppos),arlistposted.get(proppos),arlisturl.get(proppos),arlistID.get(proppos));
listView.setAdapter(adapter);
}
else
{
start=start+10;
String newurl=backurl+"&start="+start;
Log.d("URL", newurl);
Backgrounddata getData= new Backgrounddata();
getData.execute(newurl);
}
}
}
void prevProp()
{
if(Commons.HaveNetworkConnection(context))
{
if(proppos<=0)
{
btnPrev.setEnabled(false);
}
else
{
proppos--;
listView.setAdapter(null);
String[] Street={ arliststitname.get(proppos) };
adapter= new
AlertListAdapter(context,arlistimg.get(proppos), Street, arlistlocation.get(proppos),
arlistsqare.get(proppos), arlistprice.get(proppos),arlistposted.get(proppos),arlisturl.get(proppos),arlistID.get(proppos));
listView.setAdapter(adapter);
}
}
}
// background hit data
private class Backgrounddata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
for (String url : urls) {
// Create the client
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// Execute HTTP Post Request and get response
// Set connection timeout
int timeoutConnection = 15000 ;
HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), timeoutConnection);
// set socket timeout
int timeoutSocket = 15000 ;
HttpConnectionParams.setSoTimeout(httpGet.getParams(), timeoutSocket);
HttpResponse responsePOST = client.execute(httpGet);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
}
} catch (Exception e) {
return "TimeOut";
// e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
pd.dismiss();
try{
showdata(result,listView,false);
}
catch(Exception e)
{
Log.d("error hai",""+e);
}
}
#Override
protected void onPreExecute()
{
pd=new ProgressDialog(UnsignPropertyAlert.this,ProgressDialog.THEME_HOLO_LIGHT);
pd.setMessage("Loading....");
pd.setTitle(null);
pd.show();
}
}
Please Help Me How can fix this issue
Thanks In Advance

How to put custom listview row that has specific text on the top row in listview in android

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

Categories

Resources