Issue about using Async with an Android Client - android

I am currently creating a project that needs to have a simple async task to take care of a thread running behind the scenes. The user needs to login. I am using another class called PVAndroid Client that supplies useful methods and has an XML serializer form packets for me. I am completely new to working with threads or doing anything with servers, so this may be completely wrong or somewhat right.
I get the data the user entered: the ip address and port, their username (I split this into first and last name), their region they selected. I encrypt their password, and attempt to connect to the tcp using ip address and port number. I am trying to work in the async task but am kind of confused on what I should do. Can anyone guide me in the right direction and help me out?
Thank you I really appreciate it.
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String USERNAME_SHARED_PREFS = "username";
private static final String PASSWORD_SHARED_PREFS = "password";
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptedNameLoginActivity, encryptPassLoginActivity;
private EditText userText, passText;
private String getIpAddressSharedPrefs, getPortNumberPrefs;
private String getUserNameValue;
private String getPasswordValue;
private String fName, lName;
private SharedPreferences settings;
private Editor myEditor;
private boolean getCheckedRemember;
private boolean resultCheck = false;
private int portNum;
private Button submitButton;
private String userMACVARIABLE = "";
private String regionSelected, gridSelected;
private Spinner regSpinner, gridSpinner;
PVDCAndroidClient client;
private int userNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
submitButton = (Button) findViewById(R.id.submitButton);
userText = (EditText) findViewById(R.id.nameTextBox);
passText = (EditText) findViewById(R.id.passwordTextBox);
regSpinner = (Spinner) findViewById(R.id.regionSpinner);
// grid selected as well? sometime?
regSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long rowId) {
regionSelected = regSpinner.getItemAtPosition(position)
.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
submitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
settings = PreferenceManager
.getDefaultSharedPreferences(AndroidClientCompnt.this);
getIpAddressSharedPrefs = settings.getString(
IP_ADDRESS_SHARED_PREFS, "");
portNum = Integer.parseInt(settings.getString(
PORT_SHARED_PREFS, ""));
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
if (userText.length() != 0 && passText.length() != 0) {
try {
try {
// encrypting the user's password.
encryptPassLoginActivity = Secure.encrypt(passText
.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// first connect attempt.
myTcpClient = new TcpClient();
myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect.", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
}
}
});
}
private class UploadTask extends AsyncTask<String, Integer, Void>
{
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
resultCheck = myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
if (resultCheck == true) {
while (myTcpClient.getUserNum() < 0) {
// num set? session? with proxy server?
}
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = userText.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,regionSelected, 128, 128, 20);
} else {
Toast.makeText(getApplicationContext(),
"Connection not successful", Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}

First
#Override
protected Void doInBackground(String...params) {
new Thread (new Runnable() {
// ...
}
}
Never do this again. There is no need to create new Thread in doInBackground method which actually running on background Thread. So remove it.
The advice to you is tricky because you need to read about Threads, work with Connection etc. So the best advice to you is to read some tutorials, examples of basic applications and read references. So you can start here:
Android TCP Client and Server Communication Programming–Illustrated with Example

I cannot see, where you are yoursing your Task, but I see that you are doing something weired inside doInBackground()! There is absolutely NO reason, to create your own Thread inside it.
remove that, and you could just use your Task like this:
UploadTask task = new UploadTask();
task.execute("someString", "anotherString", "addAsManyStringsYouNeed");
The docs from AsyncTask are very helpfull, too.

Related

Connect my app to my SQL Server database?

I am trying to make a login screen that when the users details are entered it will connect to the MS SQL database, the problem is it is not connecting. Am I doing it the right way or is there a better way to do this?
The error I am getting.
E/ERROR: Unknown server host name 'Unable to resolve host "myipaddresstestDatabasetestDatabase": No address associated with hostname'.
Here is my code that I tried.
public class LoginActivity extends AppCompatActivity {
private static String ip = "myip";
private static String port = "myportnum";
private static String Class = "net.sourceforge.jtds.jtbc.Driver";
private static String database = "name";
private static String username = "name";
private static String password = "password";
private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
private Connection connection = null;
private EditText userNameET, passwordEt;
private Button loginBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userNameET = findViewById(R.id.userNameEditText);
passwordEt = findViewById(R.id.passEditText);
loginBTN = findViewById(R.id.loginBtn);
StrictMode.ThreadPolicy policy = null;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// #android.support.annotation.RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
private class DoLoginForUser extends AsyncTask<String, Void, String> {
String emailId, password;
#Override
protected void onPreExecute() {
super.onPreExecute();
emailId = userNameET.getText().toString();
password = passwordEt.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
loginBTN.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
try {
ConnectionHelper con = new ConnectionHelper();
Connection connect = ConnectionHelper.CONN();
String query = "Select * from testDatabase where UserId='" + emailId + "'";
PreparedStatement ps = connect.prepareStatement(query);
Log.e("query",query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String passcode = rs.getString("password");
connect.close();
rs.close();
ps.close();
if (passcode != null && !passcode.trim().equals("") && passcode.equals(password))
return "success";
else
return "Invalid Credentials";
} else
return "User does not exists.";
} catch (Exception e) {
return "Error:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show();
// ShowSnackBar(result);
// progressBar.setVisibility(View.GONE);
loginBTN.setVisibility(View.VISIBLE);
if (result.equals("success")) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email",userNameET.getText().toString());
editor.commit();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
//ShowSnackBar(result);
}
}
}
//public void ShowSnackBar(String message) {
// Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG)
// .setAction("CLOSE", new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// }
// })
// .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
// .show();
// }
public void DoLogin(View v)
{
DoLoginForUser login = null;
login = new DoLoginForUser();
login.execute("");
}
I expected it to connect and then take me to the next screen, but the error is persistent?
The error message "Unable to resolve host" indicates that you are not putting the correct sql server hostname or ip in your connection string, or you try to reach an unreachable server (from your test device).
Is the sql server reachable for you from your dev computer? If so, you may need to connect your test device via wifi.
Make sure the device and the sql server are in the same network.

Android TableView with MSSQL

I am busy with trying to get an array which i get from MSSQL to display in a table view form in my application. I have tried to google it but i cant seem to find an example of this. I have tried it but i am running into one small error.
I get the following error Cannot resolve constructor:Simpletabledata adapter[package.mainactivity, package.itemarray]
Here is my mainactivy.java class:
public class MainActivity extends AppCompatActivity {
static String[] spaceProbeHeaders={"Name"};
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
final TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
private boolean success = false; // boolean
Connection conn; // Connection Class Initialization
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableView.setHeaderBackgroundColor(Color.parseColor("#777777"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
tableView.setColumnCount(4);
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String>
{
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(MainActivity.this, "Synchronising",
"Tableview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try
{
ConnectionClass conStr=new ConnectionClass();
conn =conStr.connectionclass();
//Connection Object
if (conn == null)
{
success = false;
}
else {
// Change below query according to your own database.
String query = "SELECT customer_first_name FROM cc_customer";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next())
{
try {
itemArrayList.add(new ClassListItems(rs.getString("customer_first_name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false)
{
}
else {
try {
//myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
tableView.setDataAdapter(new SimpleTableDataAdapter(MainActivity.this,itemArrayList ));
} catch (Exception ex)
{
}
}
}
}
and here is my classlist.java file:
public class ClassListItems
{
public String name; //Name
public ClassListItems(String name)
{
this.name = name;
}
public String getName() {
return name;
}
Update
N.B: OP is using SortableTableView Library.
You need to import the following to solve Cannot resolve constructor:SimpleTableDataAdapter-
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
Original
Do you have SimpleTableDataAdapter class in your project? It seems it can't find the class so it is not in the same package. If it is in different package, you need to import it.
And on a different note, your .java file names should match the class name
And on another different note, have you tested that itemArrayList is actually populating? For Android-MSSQL, here is a tutorial pointer -
https://parallelcodes.com/connect-android-to-ms-sql-database-2/
There are many tutorials if you google it.

boolean not evaluating to true although conditions are met

So I have a static variable called isSuccessful all the variable is supposed to do is, be true if someone was able to login successfully or be false if they couldn't. I have it set to false by default. The php script I wrote sends the message "loginsuccess" and stores it in the onProgressUpdate parameters. I debugged to see if that's what was being stored in the parameters, and the compile says it is. well then I can't figure out why isSuccessful isn't being switched to true. I set it to do that. once that happens, I have the login activity call the homeScreen activity.
LoginTask:
public class LogInTask extends AsyncTask<String, String,String> {
public Scanner reader;
Formatter writer;
Context mcontext;
//if Login was successful
public static boolean isSuccessful;
LogInTask(Context context)
{
mcontext = context;
}
URL url;
URLConnection con;
String output = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
isSuccessful=false;
try {
url = new URL("http://192.168.1.75:1234/login.php");
con = url.openConnection();
//allows to send information
con.setDoOutput(true);
//allows to receive information
con.setDoInput(true);
writer = new Formatter(con.getOutputStream());
//Sends login information to SQL table
writer.format("user_name="+params[0]+"&password="+params[1]);
writer.close();
//Reads input
reader = new Scanner(con.getInputStream());
while(reader.hasNext())
{
output+= reader.next();
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(output);
return output;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mcontext, values[0],Toast.LENGTH_LONG).show();
if(values[0]=="loginsuccess")
isSuccessful = true;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
LogInActivity:
public class LogInActivity extends Activity {
private Typeface fontRobo;
private TextView logoText;
private EditText userName;
private EditText passWord;
private TextView dontHave;
private TextView signUp;
private Button logIn;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
i = new Intent(this, HomeActivity.class);
//Logo
logoText = (TextView)findViewById(R.id.Logo);
fontRobo = Typeface.createFromAsset(this.getAssets(),"fonts/ROBO.ttf");
logoText.setText("ArtSpace");
logoText.setTypeface(fontRobo);
//Don't have an account?
dontHave = (TextView) findViewById(R.id.Donthave);
dontHave.setTypeface(fontRobo);
//Sign Up
signUp = (TextView) findViewById(R.id.signUP);
signUp.setTypeface(fontRobo);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
logIn = (Button) findViewById(R.id.LogIn);
}
//Log in button event
public void logInClick(View view)
{
final LogInTask task = new LogInTask(LogInActivity.this);
task.execute(userName.getText().toString(), passWord.getText().toString());
if(LogInTask.isSuccessful)
startActivity(i);
}
php:
<?php
require "conn.php";
$user_name = $_POST['user_name'];
$user_pass = $_POST['password'];
$mysql_qry = "SELECT * FROM login WHERE UserName LIKE '$user_name' AND Password LIKE '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) == true)
{
echo "login success";
}
else
{
echo "login not success";
}
?>
task.execute() is AsyncTask aka it takes time to execute. But you are checking right after you call it. You need to make the check for isSuccessful in onPostExecute() block.
Something like this:
final LogInTask task = new LogInTask(LogInActivity.this){
#Override
protected void onPostExecute(String s) {
if(LogInTask.isSuccessful)
startActivity(i);
}};
task.execute(userName.getText().toString(), passWord.getText().toString());
PS: Something else, do not compare Strings with == use .equals()
if(values[0].equals("loginsuccess"))

How to save FUNF probes to the remote server?

I have created the funf app that only uses basic probe like wifi and simple location.At the moment the data is saved to the sd card by i want themto be save to my remote server.Thanks in advance
public class MainActivity extends Activity implements DataListener {
public static final String PIPELINE_NAME = "default";
private FunfManager funfManager;
private BasicPipeline pipeline;
private WifiProbe wifiProbe;
private SimpleLocationProbe locationProbe;
private CheckBox enabledCheckbox;
private Button archiveButton, scanNowButton;
private TextView dataCountView;
private Handler handler;
private ServiceConnection funfManagerConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
funfManager = ((FunfManager.LocalBinder)service).getManager();
Gson gson = funfManager.getGson();
wifiProbe = gson.fromJson(new JsonObject(), WifiProbe.class);
locationProbe = gson.fromJson(new JsonObject(), SimpleLocationProbe.class);
pipeline = (BasicPipeline) funfManager.getRegisteredPipeline(PIPELINE_NAME);
wifiProbe.registerPassiveListener(MainActivity.this);
locationProbe.registerPassiveListener(MainActivity.this);
// This checkbox enables or disables the pipeline
enabledCheckbox.setChecked(pipeline.isEnabled());
enabledCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (funfManager != null) {
if (isChecked) {
funfManager.enablePipeline(PIPELINE_NAME);
pipeline = (BasicPipeline) funfManager.getRegisteredPipeline(PIPELINE_NAME);
} else {
funfManager.disablePipeline(PIPELINE_NAME);
}
}
}
});
// Set UI ready to use, by enabling buttons
enabledCheckbox.setEnabled(true);
archiveButton.setEnabled(true);
scanNowButton.setEnabled(true);
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
funfManager = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Forces the pipeline to scan now
scanNowButton = (Button) findViewById(R.id.scanNowButton);
scanNowButton.setEnabled(false);
scanNowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (pipeline.isEnabled()) {
// Manually register the pipeline
wifiProbe.registerListener(pipeline);
locationProbe.registerListener(pipeline);
} else {
Toast.makeText(getBaseContext(), "Pipeline is not enabled.", Toast.LENGTH_SHORT).show();
}
}
});
// Displays the count of rows in the data
dataCountView = (TextView) findViewById(R.id.dataCountText);
// Used to make interface changes on main thread
handler = new Handler();
enabledCheckbox = (CheckBox) findViewById(R.id.enabledCheckbox);
enabledCheckbox.setEnabled(false);
// Runs an archive if pipeline is enabled
archiveButton = (Button) findViewById(R.id.archiveButton);
archiveButton.setEnabled(false);
archiveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (pipeline.isEnabled()) {
pipeline.onRun(BasicPipeline.ACTION_ARCHIVE, null);
// Wait 1 second for archive to finish, then refresh the UI
// (Note: this is kind of a hack since archiving is seamless and there are no messages when it occurs)
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Archived!", Toast.LENGTH_SHORT).show();
updateScanCount();
}
}, 1000L);
} else {
Toast.makeText(getBaseContext(), "Pipeline is not enabled.", Toast.LENGTH_SHORT).show();
}
}
});
// Bind to the service, to create the connection with FunfManager
bindService(new Intent(this, FunfManager.class), funfManagerConn, BIND_AUTO_CREATE);
}
#Override
public void onDataCompleted(IJsonObject probeConfig, JsonElement checkpoint) {
updateScanCount();
// Re-register to keep listening after probe completes.
wifiProbe.registerPassiveListener(this);
locationProbe.registerPassiveListener(this);
}
#Override
public void onDataReceived(IJsonObject arg0, IJsonObject arg1) {
// TODO Auto-generated method stub
}
private static final String TOTAL_COUNT_SQL = "SELECT count(*) FROM " + NameValueDatabaseHelper.DATA_TABLE.name;
/**
* Queries the database of the pipeline to determine how many rows of data we have recorded so far.
*/
private void updateScanCount() {
// Query the pipeline db for the count of rows in the data table
SQLiteDatabase db = pipeline.getDb();
Cursor mcursor = db.rawQuery(TOTAL_COUNT_SQL, null);
mcursor.moveToFirst();
final int count = mcursor.getInt(0);
// Update interface on main thread
runOnUiThread(new Runnable() {
#Override
public void run() {
dataCountView.setText("Data Count: " + count);
}
});
}
}
For sending data to remote server, first you need to configure your strings.xml
file like below.
"archive": {
"#schedule": {"interval": 60}
},
"upload": {
"url": \"http://example.com/test/android_data_receiver.php\",
"#schedule": {"interval": 60}
}
It will send data to server every 1 minutes and also make sure you have added
permission for accessing remote server to Android manifest file
Code for allowing permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
After done the above step please create a server file in your domain, For the
testing purpose I had created a file below. Yo can modify the file as your need.
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
You need a database on server and some backend function to add data to your remote db. The backend function should be on server, and you can call it from your Android app via HttpRequest etc.. Read about REST APIs

One Android chat app unable to receive messages ( aSamck + Openfire )

I have implemented a chat application using aSmack. I used the openfire server as the chat server. All of these applications are running in the same machine. But when I try to send messages between two emulators only one emulator successfully receives messages. Other client won't receive any messages. But from both emulators I was able to send messages to pigin(IM clinet). Also if I use gmail.com as the chat server everything works just fine.
User names used to login
jayamal
suchith
(openfire indicates users are online )
names used to send messages
jayamal#elearn (elearn is the domain i created in my machine using openfire)
suchith#elearn
( but in openfire archives shows one name as jayamal#elearn/Smack, tried sending message to that name but it also unsuccessful )
Please help to rectify this problem. Your help is really appreciated.
public class ASmackChatTestActivity extends Activity {
public int state = 0;
private static final String TAG = "HelloFormStuffActivity";
XMPPConnection xmpp ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLogin = (Button) findViewById(id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtUserName = (EditText) findViewById(id.txtUserName);
EditText txtPass = (EditText) findViewById(id.txtPass);
String userName = txtUserName.getText().toString();
String password = txtPass.getText().toString();
new login().execute(userName,password);
}
});
Button btnSend = (Button) findViewById(id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtMessage = (EditText) findViewById(id.txtMessage);
EditText txtTo = (EditText) findViewById(id.txtTo);
String message = txtMessage.getText().toString();
String to = txtTo.getText().toString();
new sendMessage().execute(to,message);
}
});
Button btnStop = (Button) findViewById(id.btnStopServices);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtTo = (EditText) findViewById(id.txtTo);
String to = txtTo.getText().toString();
new recieveMessages().execute(to);
}
});
}
class login extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String userName = params[0];
String password = params[1];
//XMPPConnection xmpp = new XMPPConnection("jabber.iitsp.com");
xmpp = new XMPPConnection("10.0.2.2");
try {
xmpp.connect();
// for other jabber accounts, truncate after the #
//xmpp.login("username", "password");
// for gtalk / gmail, include the #
xmpp.login(userName, password);
Log.v(TAG,"Logged in");
} catch (XMPPException e) {
Log.v(TAG, "Failed to connect to " + xmpp.getHost());
e.printStackTrace();
}
return null;
}
}
class sendMessage extends AsyncTask<String, Void, String>{
//String msg;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
String message = params[1];
ChatManager chatmanager = xmpp.getChatManager();
Chat newChat = chatmanager.createChat(to, new MessageListener() {
// THIS CODE NEVER GETS CALLED FOR SOME REASON
public void processMessage(Chat chat, Message message) {
try {
// msg = message.getBody();
Log.v(TAG, "Got:" + message.getBody());
chat.sendMessage(message.getBody());
} catch (XMPPException e) {
Log.v(TAG, "Couldn't respond:" + e);
}
Log.v(TAG, message.toString());
}
});
// Send something to friend#gmail.com
try {
newChat.sendMessage(message);
Log.v(TAG, "sent:" + message);
} catch (XMPPException e) {
Log.v(TAG, "couldn't send:" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(),"Message Recieved : " + msg, Toast.LENGTH_LONG);
super.onPostExecute(result);
}
}
class recieveMessages extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
// Accept only messages from friend#gmail.com
PacketFilter filter
= new AndFilter(new PacketTypeFilter(Message.class),
new FromContainsFilter(to));
// Collect these messages
PacketCollector collector = xmpp.createPacketCollector(filter);
while(true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message msg = (Message) packet;
// Process message
Log.v(TAG, "Got message: " + msg.getBody());
}
}
//return null;
}
}
}
Sorry this is a bit late.
The one user you can send to the IM client (pidgin) can you send back to your emulator. I.e. can you receive in either emulator?
Message receiving is event based so you don't need to use a button click to set it off.
Check out this great example. By Davanum Srinivas
I've modified it for my use quite extensively but the base code is still very useful.
http://davanum.wordpress.com/2008/12/29/updated-xmpp-client-for-android/ also look at the original article.

Categories

Resources