skydrive app on phonegap - android

We are trying to access skydrive using phonegap.We used an activity to call login function of skydrive. But it does not call login function at all.
Would be great help if someone shed light on this.
Here is the code.
Here activity is called from plugin class of phonegap
Intent i = new Intent(myac, DispAct.class);
try{
System.out.println("before start activity");
//i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
( this.cordova.getActivity()).startActivity(i);
}
catch(Exception e){ System.out.println("in catch"+e);}
Below code is the called activity
package org.apache.cordova;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.microsoft.live.R;
public class DispAct extends Activity
{
log obj;
private Object cordova;
private static final String APP_CLIENT_ID ="00000000400D893E" ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("disp on create");
}
#Override
protected void onStart() {
super.onStart();
System.out.println("disp on start");
obj=new log();
obj.auth = new LiveAuthClient(this.getApplicationContext(), APP_CLIENT_ID);
Iterable<String> scopes = Arrays.asList("wl.basic","wl.signin","wl.skydrive","wl.skydrive_update");
obj.auth.login(this,scopes,obj);//********this is the function which has to call login page but does not work
System.out.println("disp after login");
}
#Override
public void onResume()
{
super.onResume();
//finish();
}
}
final class log implements LiveAuthListener{
String type,message;
LiveConnectClient client;
LiveAuthClient auth;
//Parcel out;
public log()
{
//auth=new LiveAuthClient(this, message);
}
synchronized public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if(status == LiveStatus.CONNECTED) {
// this.resultTextView.setText("Signed in.");
System.out.println("IN SUCCess");
client = new LiveConnectClient(session);
//download(0);
notify();
}
else {
//this.resultTextView.setText("Not signed in.");
type="ERROR";
message="Not Connected";
client = null;
System.out.println("IN complete err");
notify();
}
}
synchronized public void onAuthError(LiveAuthException exception, Object userState) {
//this.resultTextView.setText("Error signing in: " + exception.getMessage());
client = null;
//type="ERROR";
//message="Error logging in";
System.out.println("IN error");
notify();
}
}
Here activity is displayed but login page does not appear which should appear as the result of login function

Related

Nearby.Messages API seems not to be working

I'm not being able to publish messages with Nearby.Messages, although the Subscribe method seems to be working well. I've already created new credentials for Nearby in my Google Developer Console, made sure both the SHA-1's of my computer, and the app in the PlayStore are associated with those credentials, as well as the app's package name.
As I added an OnSuccessListener to both Publish, and Subscribe, within onStart, I noticed that the Subscribe method works well, while the Publish one Fails. The error code is 2806 - Forbidden.
It used to work just the way it is. Only after I uploaded the app to the Play Store, and had to add a new OAuth 2.0 Client ID, did it stop working, on publishing the desired Message. I've maintained the previous ID, as well, so I continue testing on my device, installing from Android Studio. Meanwhile, I've also re-created both ID's in the Console, but the problem still occurs. The Nearby function is also active, on the Console.
Adding the Fragment's code below:
package co.thanker.fragments;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.messages.Message;
import com.google.android.gms.nearby.messages.MessageListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import co.thanker.R;
public class FindFragment extends Fragment {
private final String TAG = "FindFragment";
private final String OUR_USER_ID = "our-user-id";
private final String OUR_USER_COUNTRY = "our-user-country";
private final String USER_ID_STRING = "user-id-string";
private final String THANKER_ID_STRING = "thanker-id-string";
private final String USER_COUNTRY = "user-country";
private final String CONTINUE_SENDING_ID = "continue-sending-user-id";
private final String ACTIVATED_THANKS = "activated-thanks";
private Message mSendingMessage;
private MessageListener mMessageListener;
private FirebaseAuth mAuth;
private String mCountry;
private String mUserId;
private boolean mActivatedThanks;
private ImageView mGifFind;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_find, container, false);
Log.v(TAG, "Entering FindFragment");
mAuth = FirebaseAuth.getInstance();
mActivatedThanks = true;
mGifFind = (ImageView) view.findViewById(R.id.gif_find);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
if(getArguments() != null){
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() exists");
mUserId = getArguments().getString(THANKER_ID_STRING);
mCountry = getArguments().getString(OUR_USER_COUNTRY);
}
else {
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() does not exist");
mUserId = mAuth.getCurrentUser().getUid();
}
Log.v(TAG, "Nearby. Thanks got in Thanks Fragment: " + mCountry + ". User ID: " + mUserId);
if(getActivity() != null){
Glide.with(getActivity()).load(R.drawable.nearby_search).into(mGifFind);
mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN );
}
mMessageListener = new MessageListener() {
#Override
public void onFound(Message message) {
Log.d(TAG, "Nearby. Found message: " + new String(message.getContent()));
final String otherUserId = new String(message.getContent()).trim();
if(!otherUserId.equalsIgnoreCase(mAuth.getCurrentUser().getUid())){
Fragment otherUserProfileFragment = new OtherProfileFragment();
Bundle userInfoBundle = new Bundle();
userInfoBundle.putString(USER_ID_STRING, otherUserId);
userInfoBundle.putString(OUR_USER_ID, mUserId);
userInfoBundle.putString(OUR_USER_COUNTRY, mCountry);
userInfoBundle.putBoolean(ACTIVATED_THANKS, mActivatedThanks);
userInfoBundle.putBoolean(CONTINUE_SENDING_ID, true);
otherUserProfileFragment.setArguments(userInfoBundle);
if(getActivity() != null){
mProgressBar.setVisibility(View.GONE);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, otherUserProfileFragment).addToBackStack(null).commit();
}
}
}
#Override
public void onLost(Message message) {
Log.d(TAG, "Nearby. Lost sight of message: " + new String(message.getContent()));
}
};
byte [] userIdInBytes = mUserId.getBytes();
mSendingMessage = new Message(userIdInBytes);
Log.v(TAG, "Nearby. Sending Message: " + new String(mSendingMessage.getContent()));
return view;
}
#Override
public void onStart(){
super.onStart();
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).publish(mSendingMessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Publishing key");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v(TAG, "Nearby. Couldn\'t publish key. Error: " + e.toString());
}
});
Nearby.getMessagesClient(getActivity()).subscribe(mMessageListener).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Subscribing incoming message");
}
});
}
}
#Override
public void onStop(){
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).unpublish(mSendingMessage);
Nearby.getMessagesClient(getActivity()).unsubscribe(mMessageListener);
Log.v(TAG, "Nearby. Unpublished keys");
}
super.onStop();
}
}
Really appreciate your help!
Best regards,

Getting problems when using MVP model to write a "login" App

I tried to write a "login" App using MVP model. And I use WAMP to build up my server. I'm sure that my php documents have no problem.
Here is the structure of my App:
enter image description here
And here are the files:
User.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
IUserBiz.java
package com.example.android.login.mvp.biz;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserBiz
{
public void login(String username, String password, OnLoginListener loginListener);
}
OnLoginListener.java
package com.example.android.login.mvp.biz;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface OnLoginListener
{
void loginSuccess(User user);
void loginFailed();
}
UserBiz.java
package com.example.android.login.mvp.biz;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public class UserBiz extends AppCompatActivity implements IUserBiz
{
private User user;
private OnLoginListener loginListener;
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
task.execute(test1Url);
}
/**
* Update the UI with the given earthquake information.
*/
private void updateUi(User mUser) {
if (mUser.getStatus()==1)
{
loginListener.loginSuccess(user);
} else
{
loginListener.loginFailed();
}
}
private class LoginAsyncTask extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
// Perform the HTTP request for earthquake data and process the response.
User mUser = Utils.fetchEarthquakeData(urls[0],user);
return mUser;
}
#Override
protected void onPostExecute(User result) {
if(result==null){
return;
}
updateUi(result);
}
}
}
Utils.java
package com.example.android.login.mvp.biz;
import android.text.TextUtils;
import android.util.Log;
import com.example.android.login.mvp.bean.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Utility class with methods to help perform the HTTP request and
* parse the response.
*/
public final class Utils {
/** Tag for the log messages */
public static final String LOG_TAG = Utils.class.getSimpleName();
/**
* Query the USGS dataset and return an {#link User} object to represent a single earthquake.
*/
public static User fetchEarthquakeData(String requestUrl, User user) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url, user);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
// Extract relevant fields from the JSON response and create an {#link User} object
User earthquake = extractFeatureFromJson(jsonResponse);
// Return the {#link User}
return earthquake;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url, User user) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String params="app_user_name="+user.getUsername()+'&'+"app_password="+user.getPassword();
OutputStream out=urlConnection.getOutputStream();
out.write(params.getBytes());//post提交参数
out.flush();
out.close();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return an {#link User} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private static User extractFeatureFromJson(String earthquakeJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
// If there are results in the features array
if (baseJsonResponse.length() > 0) {
int status = baseJsonResponse.getInt("status");
// Create a new {#link User} object
User user=new User();
user.setStatus(status);
return user;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
UserLoginPresenter.java
package com.example.android.login.mvp.presenter;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.biz.IUserBiz;
import com.example.android.login.mvp.biz.OnLoginListener;
import com.example.android.login.mvp.biz.UserBiz;
import com.example.android.login.mvp.view.IUserLoginView;
/**
* Created by zhy on 15/6/19.
*/
public class UserLoginPresenter {
private IUserBiz userBiz;
private IUserLoginView userLoginView;
public UserLoginPresenter(IUserLoginView userLoginView) {
this.userLoginView = userLoginView;
this.userBiz = new UserBiz();
}
public void login() {
userLoginView.showLoading();
userBiz.login(userLoginView.getUserName(), userLoginView.getPassword(), new OnLoginListener() {
#Override
public void loginSuccess(final User user) {
userLoginView.toMainActivity(user);
userLoginView.hideLoading();
}
#Override
public void loginFailed() {
userLoginView.showFailedError();
userLoginView.hideLoading();
}
});
}
public void clear() {
userLoginView.clearUserName();
userLoginView.clearPassword();
}
}
IUserLoginView.java
package com.example.android.login.mvp.view;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserLoginView
{
String getUserName();
String getPassword();
void clearUserName();
void clearPassword();
void showLoading();
void hideLoading();
void toMainActivity(User user);
void showFailedError();
}
UserLoginActivity.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
But I got something wrong like this:
enter image description here
I have no idea about it. How to solve it?
the issue is here
this.userBiz = new UserBiz();
UserBiz is an activity so activity gets their context when they are being started with Intent (by OS) but creating an object of an activity will not provide any contenxt hence the null exception at
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
// no context here due to new UserBiz
// getString required context
task.execute(test1Url);
}
Solution : you can use enums or static final constants to avoid context and also would be wise to substitute UserBiz as separate class instead of an activity

My sinch client posts duplicate messages into parse database

My sinch client sends duplicate messages to my parse database in an incremental way. That is for the first message it posts once in the database. Twice for the second message. Thrice for the third in that order.
This is my ChatActivity
package com.app.knowtes;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.messaging.Message;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
import com.sinch.android.rtc.messaging.MessageFailureInfo;
import com.sinch.android.rtc.messaging.WritableMessage;
import java.util.Arrays;
import java.util.List;
/**
* Created by RR on 12/6/2015.
*/
public class ChatActivity extends ActionBarActivity {
private String recipientId;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private String currentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
ListView messagesList;
MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatactivity);
bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
//get recipientId from the intent
Intent intent = getIntent();
recipientId = intent.getStringExtra("RECIPIENT_ID");
currentUserId = ParseUser.getCurrentUser().getObjectId();
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
messagesList = (ListView) findViewById(R.id.listMessages);
messageAdapter = new MessageAdapter(this);
messagesList.setAdapter(messageAdapter);
String[] cuserIds = {currentUserId, recipientId};
String[] ruserIds = {recipientId,currentUserId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(cuserIds));
query.whereContainedIn("recipientId", Arrays.asList(ruserIds));
query.orderByAscending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < messageList.size(); i++) {
WritableMessage message = new WritableMessage(messageList.get(i).get("recipientId").toString(), messageList.get(i).get("messageText").toString());
if (messageList.get(i).get("senderId").toString().equals(currentUserId)) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_OUTGOING);
} else {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_INCOMING);
}
}
}
}
});
//listen for a click on the send button
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send the message!
messageBody = messageBodyField.getText().toString();
if (messageBody.equals("")) {
Toast.makeText(getApplicationContext(), "Please enter a message", Toast.LENGTH_SHORT).show();
return;
}else {
messageService.sendMessage(recipientId, messageBody);
messageBodyField.setText("");
}
}
});
}
//unbind the service when the activity is destroyed
#Override
public void onDestroy() {
unbindService(serviceConnection);
messageService.removeMessageClientListener(new MyMessageClientListener());
super.onDestroy();
}
private class MyServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(new MyMessageClientListener());
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
}
private class MyMessageClientListener implements MessageClientListener {
//Notify the user if their message failed to send
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
Toast.makeText(getApplicationContext(), "Message failed to send." + failureInfo.getSinchError().getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
//Display an incoming message
if (message.getSenderId().equals(recipientId)) {
WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_INCOMING);
}
}
#Override
public void onMessageSent(MessageClient client, Message message, final String recipientId) {
//Display the message that was just sent
//Later, I'll show you how to store the
//message in Parse, so you can retrieve and
//display them every time the conversation is opened
//WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
//messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
Toast.makeText(getApplicationContext(), "Message successfully senT.", Toast.LENGTH_SHORT).show();
final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
//only add message to parse database if it doesn't already exist there
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereEqualTo("sinchId", message.getMessageId());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
if (messageList.size() == 0) {
ParseObject parseMessage = new ParseObject("ParseMessage");
parseMessage.put("senderId", currentUserId);
parseMessage.put("recipientId", recipientId);
parseMessage.put("messageText", writableMessage.getTextBody());
parseMessage.put("sinchId", writableMessage.getMessageId());
parseMessage.saveInBackground();
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
}
}
}
});
}
//Do you want to notify your user when the message is delivered?
#Override
public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {}
//Don't worry about this right now
#Override
public void onShouldSendPushData(MessageClient client, Message message, List<PushPair> pushPairs) {}
}
}
And this is my MessageService.java
package com.app.knowtes;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import com.parse.ParseUser;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.WritableMessage;
/**
* Created by RR on 12/4/2015.
*/
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "XXXXXXXXXXXXXXXXXXX";
private static final String APP_SECRET = "XXXXXXXXXXXXXXXX";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private Intent broadcastIntent = new Intent("com.app.knowtes.ChatListActivity");
private LocalBroadcastManager broadcaster;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//get the current user id from Parse
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.userId(username)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
//this client listener requires that you define
//a few methods below
sinchClient.addSinchClientListener(this);
//messaging is "turned-on", but calling is not
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
//The next 5 methods are for the sinch client listener
#Override
public void onClientFailed(SinchClient client, SinchError error) {
sinchClient = null;
broadcastIntent.putExtra("success", false);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStarted(SinchClient client) {
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
broadcastIntent.putExtra("success", true);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {}
#Override
public void onLogMessage(int level, String area, String message) {}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
#Override
public void onDestroy() {
sinchClient.stopListeningOnActiveConnection();
//sinchClient.stop();
sinchClient.terminate();
}
//public interface for ListUsersActivity & MessagingActivity
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
public void terminateSinchClient(){
}
}
}
enter code here
When you log out, our servers dont know that the messages have been delivered to that device. We keep messages for delivery for 30 days. AS a developer you will experience this more since you are wiping the install when you deploy.
If you just kill the app and launch it again you will see that its not delivered again.
There is a couple of ways of avoiding this,
1. Dont log out
2. If you want logout functionality, dont toast as old messages arrive look at time stamp.
or keep track of messages id in your own database

webserver for file upload on android

I would like to add a webserver to my android application for uploading small files to the phone.
The user would start the webserver from the phone by hitting a button. He would then see an ip address that can be accessed by any browser from a pc. The website behind this ip address should show a file upload opportunity.
My question is: Is there an open source project similar to my needs? Or how would you recommend doing this?
you can use NanoHttpd link it's very weight android web server that is nicely embbedible..
package .....;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
final StringBuilder buf = new StringBuilder();
for (Entry<Object, Object> kv : header.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
}
}
}

onActivityResult in a non-activity class?

I am trying to implement facebook login and wall post in Android, so I created a non-activity class that handles everything. I saw all these examples where they use this method - onActivityResult but I don't know if I have to use it or why it's so important. Code works without it as long as I don't have the facebook app installed on the phone and I wonder if onActivityResult have anything to do with it. PS: I'm pretty sure I generated the hash key corectly. Thank you. :)
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.infobest.praiser.R;
import com.infobest.praiser.utils.Constants;
/**
* Functionality for facebook sharing
*
* #author oana_balaceanu
*
*/
public class ShareFacebook
{
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private Facebook facebook;
private String messageToPost;
private Context ctx;
public ShareFacebook(String messageToPost, Context ctx)
{
this.messageToPost = messageToPost;
this.ctx = ctx;
}
public boolean saveCredentials(Facebook facebook)
{
Editor editor = ctx.getSharedPreferences(Constants.KEY, Context.MODE_PRIVATE).edit();
editor.putString(Constants.TOKEN, facebook.getAccessToken());
editor.putLong(Constants.EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook)
{
SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(Constants.TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(Constants.EXPIRES, 0));
return facebook.isSessionValid();
}
public void share()
{
facebook = new Facebook(Constants.APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid())
{
loginAndPostToWall();
}
else
{
postToWall(messageToPost);
}
}
public void loginAndPostToWall()
{
facebook.authorize((Activity) ctx, PERMISSIONS,
(DialogListener) new LoginDialogListener());
}
public void postToWall(String message)
{
FacebookPoster fp = new FacebookPoster();
fp.execute(message, null, null);
}
private class FacebookPoster extends AsyncTask<String, Object, Object>
{
#Override
protected Object doInBackground(String... message)
{
Bundle parameters = new Bundle();
parameters.putString("message", message[0]);
parameters.putString("link", ctx.getResources().getString(R.string.rateLink));
parameters.putString("picture", ctx.getResources().getString(R.string.linkIconPicture));
try
{
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false"))
{
return ctx.getResources().getString(R.string.facebookError);
}
else
{
return ctx.getResources().getString(R.string.facebookSuccess);
}
}
catch (Exception e)
{
Log.d("ShareOnFacebook", e.toString());
return ctx.getResources().getString(R.string.facebookError);
}
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
showToast(result);
}
}
class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
saveCredentials(facebook);
if (messageToPost != null)
{
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onError(DialogError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onCancel()
{
showToast(ctx.getResources().getString(R.string.facebookCancel));
}
}
private void showToast(Object message)
{
Toast.makeText(ctx, message.toString(), Toast.LENGTH_SHORT).show();
}
}
If you test your app on emulator or smartphone with installed Facebook app, login will fail because of it.

Categories

Resources