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;
}
Related
I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();
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;
}
}
I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
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;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation
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.