【问题标题】:Migration to Parse Server (on AWS) and mLab for Android app迁移到 Parse Server(在 AWS 上)和 mLab for Android 应用程序
【发布时间】:2016-08-17 21:37:17
【问题描述】:

我有一个正在运行的 Android 应用,它正在使用 Parse.com 后端服务。我需要应用程序来调用解析服务器并使用 mLab 数据库。您能否向我展示如何在我的 Android 应用程序中从 mLab(使用 Parse Server on AWS)发送数据和获取数据的代码示例。 Parse 服务器已启动并正在运行。我已经将我的数据库从 Parse.com 迁移到了 mLab。 mLab 和 Parse 服务器已连接。

这是我在调用 parse.com URL 时使用的代码-

package com.gendertimerpro.services;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;

import com.gendertimerpro.logger.Logger;

public class Utils {

    public static String URL_SERVER_ADDRESS = "http://108.xxx.162.xxx/MyApp/";
    public static String REGISTER = "user_register.php";
    public static String LOGIN = "login.php";
    public static String FORGOT_PASSWORD = "forgot_password.php";
    public static String CREATE_GROUP = "create_group.php";
    public static String SAVE_SESSION = "save_session.php";
    public static String GET_MY_GROUP = "get_my_group.php";
    public static String GET_ALL_SESSION = "get_all_session.php";
    public static String SEND_FEEDBACK = "send_feedback.php";

    public static String PREF_NAME = "gendertimerpref";
    public static String TAG = "Utils";
    public static String USER_EMAIL = "email";
    public static String USER_PASSWORD = "password";
    public static String USER_ID = "user_id";
    public static String GENDER_TYPE = "gender_type";
    public static String Two_Three = "two_three";


    // twitter
    public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    public static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    public static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
    public static final String TWITTER_USER_NAME = "twitter_user_name";
    public static final String TWITTER_ID = "twitter_id";

    // USER
    public static final String PARSE_FACEBOOK_ID = "authData";
    public static final String PARSE_USER_ID = "user_id";
    public static final String PARSE_OBJECT_ID = "objectId";

    // GROUP
    public static final String PARSE_GROUP_NAME = "name";
//  public static final String PARSE_GROUP_NAME_CREATE_GROUP = "group_name";

    public static final String PARSE_NO_SESSIONS = "sessionCount";
    //public static final String PARSE_GROUP_RATIO = "points";
//  public static final String PARSE_GROUP_RATIO = "group_ratio";
//  public static final String PARSE_GROUP_SCORE = "points";
//  public static final String PARSE_LAST_SESSION = "last_session";
//  public static final String PARSE_LAST_SESSION_JOINTEXT = "lastSession";

    // SESSION
    public static final String PARSE_SESSION_NAME = "name";
    public static final String PARSE_NOTES = "notes";

    public static final String PARSE_NO_OF_MALE_SPEAKER = "menCount";
    public static final String PARSE_MALE_SPEAKER_TIMER = "menTime";
    public static final String PARSE_MALE_SLOTS = "menSpeakCount";

    public static final String PARSE_NO_OF_FEMALE_SPEAKER = "womenCount";
    public static final String PARSE_FEMALE_SPEAKER_TIMER = "womenTime";
    public static final String PARSE_FEMALE_SLOTS = "womenSpeakCount";

    public static final String PARSE_NO_OF_THIRD_GENDER_SPEAKER = "thirdGenderCount";
    public static final String PARSE_THIRD_GENDER_SPEAKER_TIMER = "thirdGenderTime";
    public static final String PARSE_THIRD_GENDER_SLOTS = "thirdGenderSpeakCount";

//  public static final String PARSE_SCORE = "score";
    public static final String PARSE_PRIVACY = "public";
    //public static final String PARSE_RATIO = "points";
//  public static final String PARSE_RATIO = "group_ratio";
    public static final String PARSE_POINT = "points";
    public static final String PARSE_GROUP_ID = "group";
    public static final String PARSE_GEO_POINT = "coord";
//  public static final String PARSE_LATITUDE = "latitude";
//  public static final String PARSE_LONGITUDE = "longitude";
    //public static final String TWO_THREE = "two_three";

    // FEEDBACK
    public static final String PARSE_FEEDBACK_EMAIL = "email";
    public static final String PARSE_FEEDBACK_MESSAGE = "message";
    public static final String PARSE_FEEDBACK_USER_ID = "user";

    public static boolean validateString(String object) {
        boolean flag = false;
        if (object != null && !object.isEmpty()
                && object.equalsIgnoreCase("null") != true
                && object.trim().length() > 0
                && !object.equalsIgnoreCase("(null)")) {
            flag = true;
        }
        return flag;
    }

    public static String postRequest(String url,
            List<NameValuePair> nameValuePairs) {
        String request = "";
        String result = null;
        try {
            Logger.e(TAG, "url:: " + url);
            for (NameValuePair nvp : nameValuePairs) {
                request += nvp.getName() + "=" + nvp.getValue() + "&";
            }
            Logger.e(TAG, "request:: " + request);
            // Execute HTTP Post Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 200000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) in milliseconds which
            // is the timeout for waiting for data.
            int timeoutSocket = 200000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response1 = httpclient.execute(httppost);

            result = EntityUtils.toString(response1.getEntity());
            Logger.i("TAG", "result -- " + result);
            int maxLogSize = 1000;
            int start = 0, end = 0;
            for (int i = 0; i <= result.length() / maxLogSize; i++) {
                start = i * maxLogSize;
                end = (i + 1) * maxLogSize;
                end = end > result.length() ? result.length() : end;
                Logger.i("TAG", "result str -- " + result.substring(start, end));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    public static String postRequest(String url) {
        String result = null;
        try {
            Logger.e("TAG", "url:: " + url);
            /*
             * for (NameValuePair nvp : nameValuePairs) { String name =
             * nvp.getName(); String value = nvp.getValue(); Loggger.e("TAG",
             * name +"="+value); }
             */
            // Execute HTTP Post Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 200000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) in milliseconds which
            // is the timeout for waiting for data.
            int timeoutSocket = 200000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response1 = httpclient.execute(httppost);

            result = EntityUtils.toString(response1.getEntity());

            int maxLogSize = 1000;
            int start = 0, end = 0;
            for (int i = 0; i <= result.length() / maxLogSize; i++) {
                start = i * maxLogSize;
                end = (i + 1) * maxLogSize;
                end = end > result.length() ? result.length() : end;
                Logger.i("TAG", "" + result.substring(start, end));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    public static GPSTracker getCurrentLocation(Context context) {

        GPSTracker gps = new GPSTracker(context);
        // check if GPS enabled
        if (gps.canGetLocation()) {
            // double latitude = gps.getLatitude();
            // double longitude = gps.getLongitude();
            return gps;
        } else {
            // can't get location // GPS or Network is not enabled // Ask user
            // to enable GPS/network in settings
            gps.showSettingsAlert();
        }
        return null;
    }

    //method for checking if the password matches
    public static boolean checkIfPasswordMatches(String firstPass, String secondPass){
        boolean flag=true;
        if(!firstPass.equals(secondPass)){
            flag = false;
        }
    return flag;
    }

    public static boolean checkInternetConnection(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            // Toast.makeText(context, "Conex�o com a internet indispon�vel.",
            // Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    public static final void showMessageDialog(Context context, String title,
            String message) {
        if (message != null && message.trim().length() > 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setCancelable(false);
            builder.setMessage(message);
            builder.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            // create alert dialog
            AlertDialog alertDialog = builder.create();
            // show it
            alertDialog.show();
        }
    }

    public static boolean isEmailValid(String email) {
        String expression = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        CharSequence inputStr = email;
        boolean flag = false;
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            flag = true;
        }
        return flag;
    }
}

如您所见,我没有使用 Parse.initialize(aContext, applicationId, clientKey);我应该如何更改此代码以指向 Parse 服务器

【问题讨论】:

  • 您设置解析服务器了吗?
  • 是的,我有,我只是不明白 parse 提供的代码示例。我需要一个非常简单的例子
  • 猜猜看,你没有使用 Parse :) 也许,有时你以前做过,但知道你的电话被定向到 108.xxx.162.xxx/MyApp 所以你有一个地址你自己的网络服务。
  • 但所有数据都保存在我的 Parse.com 数据库中。所以我的应用程序必须以某种方式连接到 Parse.com。你能举个例子说明我应该怎么做吗
  • 当您将数据库从 parse 迁移到 mLab 时,您会得到一个 mLab.mongo URI,例如 .... mongodb://:@ds0nnn-a0.mlab.com :nnnnn 是在您的替换服务器上使用的数据库连接器...请参阅github.com/ParsePlatform/parse-server/wiki/… 以将服务器连接到 mLab 上的数据库实例

标签: android amazon-web-services parse-platform


【解决方案1】:

嗯,

要使用 parse.com 网站,您的代码中可能有这样的地方:

Parse.initialize(aContext, applicationId, clientKey);

您现在需要将其替换为

Parse.initialize(new Parse.Configuration.Builder(aContext)
    .applicationId(applicationId)
    .server(urlOfYourOwnParseServer)
    .build());

就是这样......你已经完成了。

【讨论】:

  • 猜猜看,你没有使用 Parse :) 也许,有时你以前做过,但知道你的电话被定向到 108.xxx.162.xxx/MyApp 所以你有一个地址你自己的网络服务。
  • 啊好吧,我怎么能调用解析服务器呢?以及将代码放在哪里
猜你喜欢
  • 2019-03-21
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多