i have a big problem. My search with UserSearchManager is working fine but i dont understand how i put the results of the search in my list view.
The result type from the search is saved at a list and i wanna take the values from the row and put the result of the row in my list View in Android, but i dont get it, how i should start?
So i hope you can help me.
Moreover a have an another problem with the Iterator.
Android Studio say it cannot resolve the problem and a cast wont help me.
Iterator<Row> it = resultData.getRows();
Row row = it.next();
Iterator iterator = row.getValues("jid");
This lines are the problem. In many other threads, people have the same code snippets and theres working, but for me not.
Here is my complete code.
package de.hsrt.campusapp.app.module.xmppchat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.iqregister.packet.Registration;
import org.jivesoftware.smackx.search.ReportedData;
import org.jivesoftware.smackx.search.UserSearchManager;
import org.jivesoftware.smackx.xdata.Form;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import de.hsrt.campusapp.app.CampusAppConstants;
import de.hsrt.campusapp.app.R;
public class ActivitySearchContact extends AppCompatActivity {
private final static String serverDomain = "search.ewcexmpp1";
private static DomainBareJid serverDomainBareJid;
private ReportedData resultData;
private ListView contactList;
private EditText contactName;
private ImageButton searchContact;
private XMPPTCPConnection con = CampusAppConstants.xmppController.getNetworkManager().getXmppTCPConnection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_contact);
contactList = (ListView) findViewById(R.id.listViewForSearchAnswer);
contactName = (EditText) findViewById(R.id.editTextContactInput);
searchContact = (ImageButton) findViewById(R.id.btn_searchContactDetail);
searchContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strContact = contactName.getText().toString();
userSearch(strContact);
}
});
}
/**
* Diese Methode soll mir alle gesuchten Kontakte zurückliefern
*
* #return
*/
public ReportedData userSearch(String searchname) {
//hier eventuell die campusappconstants mit der verbindung benutzen
UserSearchManager userSearchManager = new UserSearchManager(con);
try {
Form searchForm = userSearchManager.getSearchForm(getServerDomainBareJid());
//erstellt die antwort form
Form answerForm = searchForm.createAnswerForm();
//die eigentliche suche, ich suche in der spalte Username
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", searchname);
//hier hol ich das ergebnis
this.resultData = userSearchManager.getSearchResults(answerForm, getServerDomainBareJid());
Toast.makeText(this, resultData.getRows().toString(), Toast.LENGTH_LONG).show();
if(resultData.getRows() != null)
{
Iterator<Row> it = resultData.getRows();
while(it.hasNext())
{
Row row = it.next();
Iterator iterator = row.getValues("jid");
if(iterator.hasNext())
{
String value = iterator.next().toString();
Log.i("Iteartor values......"," "+value);
}
//Log.i("Iteartor values......"," "+value);
}
Toast.makeText(this,"Username Exists",Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
e.printStackTrace();
e.getMessage();
//Log.e(this.getClass().getSimpleName().toString(), "Fehler bei der Suche", e);
}
return this.resultData;
}
private static DomainBareJid getServerDomainBareJid() {
try {
serverDomainBareJid = JidCreate.domainBareFrom(serverDomain);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
return serverDomainBareJid;
}
}
Related
I am trying to add a for loop or while loop for method getuserDetailWhileLoop(); but i am having a hard time figuring out on how to do it. This code suppose to show json object to text view and text view has scroll view in it. However when i ran the code the while loop is not working and only show 1 object. I need the while loop to show multiple object. How will i be doing that? Thanks.
package com.demo.myblog.profile;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.demo.myblog.R;
import com.demo.myblog.volley.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class UserProfile extends AppCompatActivity {
private String ID,NAME,EMAIL,CREATED_DATE, ID2;
private String appURl, appURl2;
Activity mContext = this;
TextView mId,mName,mEmail,mDate, mid2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile2);
mId = findViewById(R.id.txt_Id);
mid2 = findViewById(R.id.textView5);
mName = findViewById(R.id.txt_Name);
mEmail = findViewById(R.id.txt_Email);
mDate = findViewById(R.id.txt_Data);
Intent data = getIntent();
EMAIL = data.getStringExtra("email");
appURl = "url here";
appURl2 = "url2 here";
getUserDetail();
getuserDetailWhileLoop();
}
private void getuserDetailWhileLoop()
{
if (EMAIL.isEmpty()){
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Email cannot be empty");
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
else{
StringRequest stringRequest = new StringRequest(Request.Method.GET,appURl2, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try
{
JSONObject jo = new JSONObject( response );
for(int i =0 ;i < jo.length(); i++)
{
ID2 = jo.getString( "id" );
//NAME = jsonObject.getString("username");
//EMAIL = jsonObject.getString("user_email");
//CREATED_DATE = jsonObject.getString("created_date");
//sonObject = jsonObject.getJSONObject( "id" );
mid2.setText( ID2 );
//mName.setText(NAME);
//mEmail.setText(EMAIL);
//mDate.setText(CREATED_DATE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I like to use for loops over while loops, because with a for loop you're able to check the progress of the loop.
In this case it is best to use a for loop, just like you already did.
Can you post a example response of the StringRequest?
[EDIT]
You forgot to add the counter 'i', your for loop is fine.
JSONObject obj = jo.getJSONObject(i);
obj.getString("id");
I think this is the solution to your problem.
I'm trying to pull all the data from a table using SELECT * from book, but I'm getting:
Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
I got it working when triggering the SQL statement in Eclipse. I'm trying to recreate it in Android Studio, but seems to throw this issue. Any help is appreciated.
SQL.java
package com.example.andy.loginapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by Andy on 1/4/2017.
*/
public class SQL {
private Statement st;
private Connection con;
private ResultSet rs;
public SQL(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sqltest", "root", "");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e);
}
}
public void getData(){
try{
String query = "SELECT * from book";
String queryInsert = "INSERT into Book " + "VALUE(authorField.getText(), titleField.getText(), yearField.getText())";
rs = st.executeQuery(query);
while(rs.next()){
String author = rs.getString("author");
String title = rs.getString("title");
System.out.println("Author: " + author + " " + "Title" + " " + title);
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("success");
}
}
MainActivity.java
package com.example.andy.loginapp;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private Statement st;
private Connection con;
private ResultSet rs;
TextView hi;
RelativeLayout background;
Button sqlButton;
SQL data = new SQL();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlButton = (Button) findViewById(R.id.sqlButton);
sqlButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
data.getData();
}
});
}
}
You would have to write a webservice to connect to any external databases such as MYSQL to connect android application to a database. It also involves writing a very basic PHP script.
See the following link for some examples.
https://www.b4x.com/android/forum/threads/connect-android-to-mysql-database-tutorial.8339/
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
So you're better off using SQLLite unless its absolutely necessary.
I am using below code and my textview links are clickable but i want to make specific button of whatsapp and facebook for sharing..i referred several article in stackoverflow but i want for textview. for webview i had earlier done and it was easy .please help /suggest for textview sharing. i dont want all buttons to open. i want after each listview one facebook and whatsapp icon. on click whatsapp should open with text to be shared
in textview i am adding below for whatsapp share but nothing happens
<a rel="nofollow" href="whatsapp://send?text=एक वृद्ध दंपति को लगने लगा कि उनकी क वृद्ध दंपति को लगने लगा कि उनकी याददाश्त कमजोर हो चली है। यह सुनिश्चित करने के लिये कि उन्हें कुछ नही%0A."><span class="whatsapp"> </span></a>
my java code is
tried adding this one also in java but no benefit.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(Intent.createChooser(intent, ""));
main.java code here
package com.hindishayari.funnywall.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import com.hindishayari.funnywall.R;
import com.hindishayari.funnywall.adapter.SwipeDownListAdapter;
import com.hindishayari.funnywall.analytics.AnalyticsApplication;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
// URLS for Fetching and Submitting to Funny Wall.
private String FetchFunnyWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/ppppppppp.php";
private String SubmitJokeToWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/hhhhhhhhhh.php";
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeDownListAdapter adapter;
private ArrayList<String> jokesList;
private ArrayList<String> timeDateList;
String JokeString = null;
String []dataValues = new String[2];
int counter = 0;
TextView titleTextView;
AlertDialog alertDw;
AlertDialog.Builder builder;
Typeface font;
LinearLayout adViewLayout;
LinearLayout listViewLayout;
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
font = Typeface.createFromAsset(getAssets(), "HelveticaNeue-Regular.ttf");
titleTextView = (TextView) findViewById(R.id.titleID);
adViewLayout = (LinearLayout) findViewById(R.id.adViewLayoutID);
listViewLayout = (LinearLayout) findViewById(R.id.ListViewLinearLayout);
titleTextView.setTypeface(font);
dataValues[0] = "";
dataValues[1] = "";
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
jokesList = new ArrayList<>();
timeDateList = new ArrayList<>();
adapter = new SwipeDownListAdapter(this, jokesList, timeDateList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
}
);
/*
This function is to refresh the List with Swipe-Down
*/
#Override
public void onRefresh() {
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
#Override
protected void onResume() {
super.onResume();
}
/*
This function is to fetch all the jokes + dates from the server and store that into the jokesList
timeDateLis respectively
*/
private class FetchFunnyWallFromServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return FetchFunnyWall(urls[0]);
} catch (IOException e) {
return "Sorry, We cannot retrieve credits data form the server at this moment.";
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listView.setEnabled(false);
dataValues[0] = "";
dataValues[1] = "";
counter = 0;
jokesList.clear();
timeDateList.clear();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
swipeRefreshLayout.setRefreshing(false);
listView.setEnabled(true);
if (result.equals("OK")) {
listView.post(new Runnable() {
#Override
public void run() {
Collections.reverse(jokesList);
Collections.reverse(timeDateList);
adapter.notifyDataSetChanged();
listView.smoothScrollToPosition(0);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Network Connection Problem. Make sure that your internet is properly connected", Toast.LENGTH_SHORT).show();
}
}
}
private String FetchFunnyWall(String myurl) throws IOException, UnsupportedEncodingException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
BufferedReader textReader = new BufferedReader(new InputStreamReader(is));
String readlineText;
while ((readlineText = textReader.readLine()) != null) {
if (readlineText.length() > 0 )
{
if (readlineText.equals("****")) {
continue;
}
if (readlineText.length() < 4) {
continue;
}
for (int i = 0; i < readlineText.length(); ++i) {
if (readlineText.charAt(i) == '|') {
++counter;
continue;
}
dataValues[counter] = (dataValues[counter] + readlineText.charAt(i));
}
jokesList.add(dataValues[0]);
timeDateList.add(dataValues[1]);
counter = 0;
dataValues[0] = "";
dataValues[1] = "";
}
}
}
}
}
any help will be great
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.
I have gone through this1, this2 and this3 but still cannot find the solution of the problem.
I could know where my problem is what I am doing in this code is:
Take the input from textbox and
Pass that value to check if the username supplied in the textbox exists or not
Whenever I click check button only "Function called" is displayed and is not performing search.
Here is my code what I done so far.
public class Registration extends Activity implements OnClickListener {
private final static String SERVER_HOST = "10.0.2.2";
private final static int SERVER_PORT = 5222;
private static final String TAG = null;
private ProviderManager pm;
private EditText username;
private Button btn;
private XMPPConnection connection;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
try {
initConnection();
} catch (XMPPException e) {
e.printStackTrace();
}
username = (EditText) this.findViewById(R.id.txtregusername);
btn=(Button) this.findViewById(R.id.btncheck);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btncheck:
try {
check();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
private void check() throws XMPPException{
Toast.makeText(this,"Function called",Toast.LENGTH_SHORT).show();
pm.addIQProvider("query","jabber:iq:search", new UserSearch.Provider());
UserSearchManager search = new UserSearchManager(connection);
Form searchForm = search.getSearchForm("search."+connection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
Toast.makeText(this,username.getText().toString(),Toast.LENGTH_SHORT).show();
answerForm.setAnswer("search", username.getText().toString());
ReportedData data = search.getSearchResults(answerForm,"search."+connection.getServiceName());
if(data.getRows() != null)
{
Toast.makeText(this,"Username Exists",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,"Username Available",Toast.LENGTH_SHORT).show();
}
}
private void initConnection() throws XMPPException{
ConnectionConfiguration config=new ConnectionConfiguration(SERVER_HOST,SERVER_PORT);
config.setSecurityMode(SecurityMode.enabled);
config.setSASLAuthenticationEnabled(true);
connection=new XMPPConnection(config);
try {
connection.connect();
}
catch (XMPPException e) {
Log.e(TAG, "Error connection to XMPP Server");
e.printStackTrace();
}
}
}
Try this. It solves my problem.
UserSearchManager search = new UserSearchManager(mXMPPConnection);
Form searchForm = search.getSearchForm("search."+mXMPPConnection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", user);
org.jivesoftware.smackx.ReportedData data = search.getSearchResults(answerForm,"search."+mXMPPConnection.getServiceName());
if(data.getRows() != null)
{
Iterator<Row> it = data.getRows();
while(it.hasNext())
{
Row row = it.next();
Iterator iterator = row.getValues("jid");
if(iterator.hasNext())
{
String value = iterator.next().toString();
Log.i("Iteartor values......"," "+value);
}
//Log.i("Iteartor values......"," "+value);
}
Toast.makeText(_service,"Username Exists",Toast.LENGTH_SHORT).show();
);
}
If Server has not any entery with that specified name then Itearator it has no value and code will not go inside while(it.hasNext).
Hi you need to use ProviderManager first, otherwise search will not work properly.Below is my working code which works perfectly, Hope it will help:
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PrivacyList;
import org.jivesoftware.smack.PrivacyListManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.PrivacyItem;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.GroupChatInvitation;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.ReportedData.Row;
import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smackx.packet.LastActivity;
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
import org.jivesoftware.smackx.packet.OfflineMessageRequest;
import org.jivesoftware.smackx.packet.SharedGroupsInfo;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;
import org.jivesoftware.smackx.provider.DataFormProvider;
import org.jivesoftware.smackx.provider.DelayInformationProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
import org.jivesoftware.smackx.provider.MUCAdminProvider;
import org.jivesoftware.smackx.provider.MUCOwnerProvider;
import org.jivesoftware.smackx.provider.MUCUserProvider;
import org.jivesoftware.smackx.provider.MessageEventProvider;
import org.jivesoftware.smackx.provider.MultipleAddressesProvider;
import org.jivesoftware.smackx.provider.RosterExchangeProvider;
import org.jivesoftware.smackx.provider.StreamInitiationProvider;
import org.jivesoftware.smackx.provider.VCardProvider;
import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;
import org.jivesoftware.smackx.search.UserSearch;
import org.jivesoftware.smackx.search.UserSearchManager;
public static List<String> getUserListBySearch(XMPPConnection mXMPPConnection, String searchString){
ProviderManager.getInstance().addIQProvider("query","jabber:iq:search", new UserSearch.Provider());
List<String> l = new ArrayList<String>();
try {
UserSearchManager search = new UserSearchManager(mXMPPConnection);
Form searchForm = search.getSearchForm("search."+mXMPPConnection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", searchString);
org.jivesoftware.smackx.ReportedData data = search.getSearchResults(answerForm,"search."+mXMPPConnection.getServiceName());
if(data.getRows() != null)
{
Iterator<Row> it = data.getRows();
while(it.hasNext())
{
Row row = it.next();
System.out.println(row);
Iterator iterator = row.getValues("jid");
if(iterator.hasNext())
{
String value = iterator.next().toString();
l.add(value);
System.out.println("Iteartor values......"+value);
}
//Log.i("Iteartor values......"," "+value);
}
System.out.println("UserName Exists");
}
} catch (Exception e) {
System.out.println("Exception in Loading user search"+e);
}
return l;
}