Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

In this page you can find the example usage for android.app ProgressDialog dismiss.

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.shafiq.myfeedle.core.MyfeedleComments.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0)
                && (mSid != null) && (mEsid != null)) {
            mMessage.setEnabled(false);//from   www  . ja va  2  s  . c  o m
            mSend.setEnabled(false);
            // post or comment!
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    List<NameValuePair> params;
                    String message;
                    String response = null;
                    HttpPost httpPost;
                    MyfeedleOAuth myfeedleOAuth;
                    String serviceName = Myfeedle.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                        myfeedleOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case FACEBOOK:
                        httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid,
                                Saccess_token, mToken));
                        params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                    MYSPACE_BASE_URL, mEsid, mSid));
                            httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY,
                                    mMessage.getText().toString())));
                            response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                    myfeedleOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case FOURSQUARE:
                        try {
                            message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                            httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL,
                                    mSid, message, mToken));
                            response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(
                                    String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                            httpPost.setEntity(new StringEntity(
                                    String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString())));
                            httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                            response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                    myfeedleOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                        myfeedleOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case GOOGLEPLUS:
                        break;
                    case CHATTER:
                        httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid,
                                Uri.encode(mMessage.getText().toString())));
                        httpPost.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                        break;
                    }
                    return ((response == null) && (mService == MYSPACE)) ? null
                            : serviceName + " "
                                    + getString(response != null ? R.string.success : R.string.failure);
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result != null) {
                        (Toast.makeText(MyfeedleComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(MyfeedleComments.this,
                                MyfeedleComments.this.getResources()
                                        .getStringArray(R.array.service_entries)[MYSPACE]
                                        + getString(R.string.failure) + " "
                                        + getString(R.string.myspace_permissions_message),
                                Toast.LENGTH_LONG)).show();
                    }
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else {
            (Toast.makeText(MyfeedleComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}

From source file:com.piusvelte.sonet.SonetComments.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0)
                && (mSid != null) && (mEsid != null)) {
            mMessage.setEnabled(false);//from  w w w.  j a  v a 2  s.c om
            mSend.setEnabled(false);
            // post or comment!
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    List<NameValuePair> params;
                    String message;
                    String response = null;
                    HttpPost httpPost;
                    SonetOAuth sonetOAuth;
                    String serviceName = Sonet.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken,
                                mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case FACEBOOK:
                        httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid,
                                Saccess_token, mToken));
                        params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken,
                                mSecret);
                        try {
                            httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                    MYSPACE_BASE_URL, mEsid, mSid));
                            httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY,
                                    mMessage.getText().toString())));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case FOURSQUARE:
                        try {
                            message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                            httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL,
                                    mSid, message, mToken));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET,
                                mToken, mSecret);
                        try {
                            httpPost = new HttpPost(
                                    String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                            httpPost.setEntity(new StringEntity(
                                    String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString())));
                            httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET,
                                mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case GOOGLEPLUS:
                        break;
                    case CHATTER:
                        httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid,
                                Uri.encode(mMessage.getText().toString())));
                        httpPost.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        break;
                    }
                    return ((response == null) && (mService == MYSPACE)) ? null
                            : serviceName + " "
                                    + getString(response != null ? R.string.success : R.string.failure);
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result != null) {
                        (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(SonetComments.this,
                                SonetComments.this.getResources()
                                        .getStringArray(R.array.service_entries)[MYSPACE]
                                        + getString(R.string.failure) + " "
                                        + getString(R.string.myspace_permissions_message),
                                Toast.LENGTH_LONG)).show();
                    }
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else {
            (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    System.gc();//from   w  ww  . ja v  a  2 s. co m
    if (requestCode == 34) {
        if (resultCode == activity.RESULT_OK) {
            Uri contactUri = data.getData();
            try {
                //contactPic.setImageBitmap(getPhoto(contactUri));
                JSONObject contactoSend = new JSONObject();
                contactoSend.put("nombre", getName(contactUri));
                contactoSend.put("telefono", getPhone(contactUri));
                MsgGroups msjNew = new MsgGroups();
                Calendar fecha = Calendar.getInstance();
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                String contactosId = null;
                if (SpeakSocket.mSocket != null) {
                    if (SpeakSocket.mSocket.connected()) {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (translate)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", 1);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    } else {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (translate)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", -1);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    }
                }
                msjNew.grupoId = grupo.grupoId;
                msjNew.mensajeId = u.id + grupo.grupoId + fecha.getTimeInMillis()
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjNew.emisor = u.id;
                msjNew.receptores = targets.toString();
                msjNew.mensaje = contactoSend.toString();
                msjNew.emisorEmail = u.email;
                msjNew.emisorLang = u.lang;
                msjNew.translation = false;
                msjNew.emitedAt = fecha.getTimeInMillis();
                msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_CONTACT));
                msjNew.delay = 0;
                msjNew.save();
                showNewMessage(msjNew);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.gc();
    }

    if (requestCode == 1 && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        Bitmap bitmapRotate = C.rotateBitmapAndScale(picturePath);
        cursor.close();
        System.gc();
        Calendar fecha = Calendar.getInstance();
        long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
        pathImage.mkdirs();
        Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
        System.gc();
        Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
        System.gc();
        Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
        System.gc();
        File file = new File(pathImage, +fechaInMillis + ".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
            outputStream.flush();
            outputStream.close();
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            final MsgGroups msjPhoto = new MsgGroups();
            JSONArray targets = new JSONArray();
            JSONArray contactos = new JSONArray(grupo.targets);
            String contactosId = null;
            if (SpeakSocket.mSocket != null) {
                if (SpeakSocket.mSocket.connected()) {
                    for (int i = 0; i < contactos.length(); i++) {
                        JSONObject contacto = contactos.getJSONObject(i);
                        JSONObject newContact = new JSONObject();
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", contacto.getString("name")).executeSingle();
                        if (contact != null) {
                            if (!contact.idContacto.equals(u.id)) {
                                if (translate)
                                    newContact.put("lang", contact.lang);
                                else
                                    newContact.put("lang", u.lang);
                                newContact.put("name", contact.idContacto);
                                newContact.put("screen_name", contact.screenName);
                                newContact.put("status", 1);
                                contactosId += contact.idContacto;
                                targets.put(targets.length(), newContact);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < contactos.length(); i++) {
                        JSONObject contacto = contactos.getJSONObject(i);
                        JSONObject newContact = new JSONObject();
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", contacto.getString("name")).executeSingle();
                        if (contact != null) {
                            if (!contact.idContacto.equals(u.id)) {
                                if (translate)
                                    newContact.put("lang", contact.lang);
                                else
                                    newContact.put("lang", u.lang);
                                newContact.put("name", contact.idContacto);
                                newContact.put("screen_name", contact.screenName);
                                newContact.put("status", -1);
                                contactosId += contact.idContacto;
                                targets.put(targets.length(), newContact);
                            }
                        }
                    }
                }
            }
            msjPhoto.grupoId = grupo.grupoId;
            msjPhoto.mensajeId = u.id + grupo.grupoId + fechaInMillis
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
            msjPhoto.emisor = u.id;
            msjPhoto.receptores = targets.toString();
            msjPhoto.mensaje = "send Image";
            msjPhoto.emisorEmail = u.email;
            msjPhoto.emisorLang = u.lang;
            msjPhoto.translation = false;
            msjPhoto.emitedAt = fechaInMillis;
            msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_PHOTO));
            msjPhoto.delay = 0;
            msjPhoto.photoName = file.getAbsolutePath();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            msjPhoto.photo = byteArray;

            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
            byte[] byteArray2 = stream2.toByteArray();
            msjPhoto.photoBlur = byteArray2;
            msjPhoto.fileUploaded = false;
            msjPhoto.save();
            showNewMessage(msjPhoto);
        } catch (Exception e) {
        }
        System.gc();
    }

    if (requestCode == 23) {
        if (resultCode == Activity.RESULT_OK) {
            Bitmap bitmapRotate = C
                    .rotateBitmapAndScale(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            System.gc();
            Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
            System.gc();
            Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
            System.gc();
            Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
            System.gc();
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                outputStream.flush();
                outputStream.close();
                System.gc();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                final MsgGroups msjPhoto = new MsgGroups();
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                String contactosId = null;
                if (SpeakSocket.mSocket != null) {
                    if (SpeakSocket.mSocket.connected()) {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (translate)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", 1);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    } else {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (translate)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", -1);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    }
                }
                msjPhoto.grupoId = grupo.grupoId;
                msjPhoto.mensajeId = u.id + grupo.grupoId + dateToCamera
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjPhoto.emisor = u.id;
                msjPhoto.receptores = targets.toString();
                msjPhoto.mensaje = "send Image";
                msjPhoto.emisorEmail = u.email;
                msjPhoto.emisorLang = u.lang;
                msjPhoto.translation = false;
                msjPhoto.emitedAt = dateToCamera;
                msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_PHOTO));
                msjPhoto.delay = 0;
                msjPhoto.photoName = file.getAbsolutePath();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] byteArray = stream.toByteArray();
                msjPhoto.photo = byteArray;

                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                byte[] byteArray2 = stream2.toByteArray();
                msjPhoto.photoBlur = byteArray2;
                msjPhoto.fileUploaded = false;
                msjPhoto.save();
                showNewMessage(msjPhoto);
            } catch (Exception e) {
            }
            System.gc();
        }
    }

    System.gc();
    if (requestCode == 18 && resultCode == Activity.RESULT_OK && null != data) {
        final ProgressDialog dialogLoader = ProgressDialog.show(activity, "",
                Finder.STRING.CONTACT_PROGRESS.toString(), true);
        Uri selectedVideo = data.getData();
        String[] filePathColumn = { MediaStore.Video.Media.DATA };
        final Cursor cursor = activity.getContentResolver().query(selectedVideo, filePathColumn, null, null,
                null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        final String videoPath = cursor.getString(columnIndex);
        cursor.close();
        System.gc();
        final File fileVideo = new File(videoPath);
        Calendar fecha = Calendar.getInstance();
        final long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent");
        pathImage.mkdirs();
        final File file = new File(pathImage, +fechaInMillis + ".mp4");
        cursor.close();
        //runTranscodingUsingLoader(fileVideo.getAbsolutePath(), file.getAbsolutePath());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoPath,
                        MediaStore.Video.Thumbnails.MICRO_KIND);
                Bitmap toUpload = scaleDownLargeImageWithAspectRatio(thumbnailVideo, 1280);
                Bitmap binaryData = toUpload;
                Bitmap binaryData2 = BlurImage(toUpload);
                try {
                    FileInputStream inStream = new FileInputStream(fileVideo);
                    FileOutputStream outStream = new FileOutputStream(file);

                    byte[] buffer = new byte[1024];

                    int length;
                    //copy the file content in bytes
                    while ((length = inStream.read(buffer)) > 0) {

                        outStream.write(buffer, 0, length);

                    }

                    inStream.close();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    final MsgGroups msjVideo = new MsgGroups();
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    String contactosId = null;
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        }
                    }
                    msjVideo.grupoId = grupo.grupoId;
                    msjVideo.mensajeId = u.id + grupo.grupoId + fechaInMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjVideo.emisor = u.id;
                    msjVideo.receptores = targets.toString();
                    msjVideo.mensaje = "send Video";
                    msjVideo.emisorEmail = u.email;
                    msjVideo.emisorLang = u.lang;
                    msjVideo.translation = false;
                    msjVideo.emitedAt = fechaInMillis;
                    msjVideo.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_VIDEO));
                    msjVideo.delay = 0;
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] byteArray = stream.toByteArray();
                    msjVideo.photo = byteArray;
                    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                    binaryData2.compress(Bitmap.CompressFormat.JPEG, 60, stream2);
                    byte[] byteArray2 = stream2.toByteArray();
                    msjVideo.photoBlur = byteArray2;
                    msjVideo.fileUploaded = false;
                    msjVideo.videoName = file.getAbsolutePath();
                    msjVideo.save();
                    showNewMessage(msjVideo);
                    dialogLoader.dismiss();
                } catch (Exception e) {
                }
                System.gc();
            }
        }).start();

    }

    if (requestCode == 45) {
        milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = milocManager.getAllProviders();
        boolean gpsProvider = false;
        boolean netProvider = false;
        for (String providerName : allProviders) {
            if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                gpsProvider = true;
            }
            if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                netProvider = true;
            }
        }
        checkCountryLocation(gpsProvider, netProvider);
    }

}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    System.gc();// ww w  .  ja  v  a  2 s. co  m
    if (requestCode == 18 && resultCode == Activity.RESULT_OK && null != data) {
        final ProgressDialog dialogLoader = ProgressDialog.show(activity, "",
                Finder.STRING.CONTACT_PROGRESS.toString(), true);
        Uri selectedVideo = data.getData();
        String[] filePathColumn = { MediaStore.Video.Media.DATA };
        final Cursor cursor = activity.getContentResolver().query(selectedVideo, filePathColumn, null, null,
                null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        final String videoPath = cursor.getString(columnIndex);
        cursor.close();
        System.gc();
        final File fileVideo = new File(videoPath);
        Calendar fecha = Calendar.getInstance();
        final long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent");
        pathImage.mkdirs();
        final File file = new File(pathImage, +fechaInMillis + ".mp4");
        cursor.close();
        //runTranscodingUsingLoader(fileVideo.getAbsolutePath(), file.getAbsolutePath());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoPath,
                        MediaStore.Video.Thumbnails.MICRO_KIND);
                Bitmap toUpload = scaleDownLargeImageWithAspectRatio(thumbnailVideo, 1280);
                Bitmap binaryData = toUpload;
                Bitmap binaryData2 = BlurImage(toUpload);
                try {
                    FileInputStream inStream = new FileInputStream(fileVideo);
                    FileOutputStream outStream = new FileOutputStream(file);

                    byte[] buffer = new byte[1024];

                    int length;
                    //copy the file content in bytes
                    while ((length = inStream.read(buffer)) > 0) {

                        outStream.write(buffer, 0, length);

                    }

                    inStream.close();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final Message msjVideo = new Message();
                try {
                    String id = u.id + contact.idContacto + fechaInMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);

                    msjVideo.mensajeId = id;
                    msjVideo.emisor = u.id;
                    msjVideo.receptor = contact.idContacto;
                    msjVideo.emisorEmail = u.email;
                    msjVideo.receptorEmail = contact.email;
                    msjVideo.emisorLang = u.lang;
                    msjVideo.receptorLang = contact.lang;
                    msjVideo.emitedAt = fechaInMillis;
                    msjVideo.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_VIDEO));
                    if (tiempoMensaje)
                        msjVideo.delay = temporizadorSeek.getValue();
                    else
                        msjVideo.delay = 0;
                    msjVideo.videoName = file.getAbsolutePath();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] byteArray = stream.toByteArray();
                    msjVideo.photo = byteArray;

                    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                    binaryData2.compress(Bitmap.CompressFormat.JPEG, 60, stream2);
                    byte[] byteArray2 = stream2.toByteArray();
                    msjVideo.photoBlur = byteArray2;
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjVideo.status = 1;
                        } else {
                            msjVideo.status = -1;
                        }
                    msjVideo.fileUploaded = false;
                    msjVideo.save();

                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjVideo.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjVideo.receptor).executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjVideo.mensajeId;
                        newChat.idContacto = msjVideo.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjVideo.status;
                        newChat.email = msjVideo.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjVideo.receptorEmail;
                            newChat.lang = msjVideo.receptorLang;
                            newChat.screenName = msjVideo.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjVideo.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Video";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjVideo.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjVideo.mensajeId;
                        chat.lastStatus = msjVideo.status;
                        chat.emitedAt = msjVideo.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Video";
                        chat.save();
                    }
                    showNewMessage(msjVideo);
                    dialogLoader.dismiss();
                } catch (Exception e) {
                }
                System.gc();
            }
        }).start();

    }

    if (requestCode == 45) {
        milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = milocManager.getAllProviders();
        boolean gpsProvider = false;
        boolean netProvider = false;
        for (String providerName : allProviders) {
            if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                gpsProvider = true;
            }
            if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                netProvider = true;
            }
        }
        checkCountryLocation(gpsProvider, netProvider);
    }

    if (requestCode == 34) {
        if (resultCode == activity.RESULT_OK) {
            Uri contactUri = data.getData();
            try {
                //contactPic.setImageBitmap(getPhoto(contactUri));
                JSONObject contacto = new JSONObject();
                contacto.put("nombre", getName(contactUri));
                contacto.put("telefono", getPhone(contactUri));
                Message msjNew = new Message();
                Calendar fecha = Calendar.getInstance();
                String id = u.id + contact.idContacto + fecha.getTimeInMillis()
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjNew.translation = true;
                msjNew.mensajeId = id;
                msjNew.emisor = u.id;
                msjNew.receptor = contact.idContacto;
                msjNew.mensaje = contacto.toString();
                msjNew.emisorEmail = u.email;
                msjNew.receptorEmail = contact.email;
                msjNew.emisorLang = u.lang;
                msjNew.receptorLang = contact.lang;
                msjNew.emitedAt = fecha.getTimeInMillis();
                msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_CONTACT));
                msjNew.delay = 0;
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        msjNew.status = 1;
                    } else {
                        msjNew.status = -1;
                    }
                msjNew.save();
                Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjNew.receptor)
                        .executeSingle();
                if (chat == null) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.receptor)
                            .executeSingle();
                    Chats newChat = new Chats();
                    newChat.mensajeId = msjNew.mensajeId;
                    newChat.idContacto = msjNew.receptor;
                    newChat.isLockedConversation = false;
                    newChat.lastStatus = msjNew.status;
                    newChat.email = msjNew.receptorEmail;
                    if (contact != null) {
                        newChat.photo = contact.photo;
                        newChat.fullName = contact.fullName;
                        newChat.lang = contact.lang;
                        newChat.screenName = contact.screenName;
                        newChat.photoload = true;
                        newChat.phone = contact.phone;
                    } else {
                        newChat.photo = null;
                        newChat.photoload = false;
                        newChat.fullName = msjNew.receptorEmail;
                        newChat.lang = msjNew.receptorLang;
                        newChat.screenName = msjNew.receptorEmail;
                        newChat.phone = null;
                    }
                    newChat.emitedAt = msjNew.emitedAt;
                    newChat.notRead = 0;
                    newChat.lastMessage = "send Contact";
                    newChat.show = true;
                    newChat.save();
                } else {
                    if (!chat.photoload) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjNew.emisor).executeSingle();
                        if (contact != null) {
                            chat.photo = contact.photo;
                            chat.photoload = true;
                        } else {
                            chat.photo = null;
                            chat.photoload = false;
                        }
                    }
                    chat.mensajeId = msjNew.mensajeId;
                    chat.lastStatus = msjNew.status;
                    chat.emitedAt = msjNew.emitedAt;
                    chat.notRead = 0;
                    chat.lastMessage = "send Contact";
                    chat.save();
                }
                showNewMessage(msjNew);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.gc();
    }
    if (requestCode == 1 && null != data) {
        Uri selectedImage = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = activity.getContentResolver().openInputStream(selectedImage);
        } catch (FileNotFoundException e) {
        }
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        Bitmap bitmapRotate = C.rotateBitmapAndScale(picturePath);
        cursor.close();
        System.gc();
        Calendar fecha = Calendar.getInstance();
        long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
        pathImage.mkdirs();
        Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
        System.gc();
        Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
        System.gc();
        Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
        System.gc();
        File file = new File(pathImage, +fechaInMillis + ".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
            outputStream.flush();
            outputStream.close();
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            final Message msjPhoto = new Message();
            String id = u.id + contact.idContacto + fechaInMillis
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
            msjPhoto.mensajeId = id;
            msjPhoto.emisor = u.id;
            msjPhoto.receptor = contact.idContacto;
            msjPhoto.emisorEmail = u.email;
            msjPhoto.receptorEmail = contact.email;
            msjPhoto.emisorLang = u.lang;
            msjPhoto.receptorLang = contact.lang;
            msjPhoto.emitedAt = fechaInMillis;
            msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
            if (tiempoMensaje)
                msjPhoto.delay = temporizadorSeek.getValue();
            else
                msjPhoto.delay = 0;
            msjPhoto.photoName = file.getAbsolutePath();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            msjPhoto.photo = byteArray;

            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
            byte[] byteArray2 = stream2.toByteArray();
            msjPhoto.photoBlur = byteArray2;
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    msjPhoto.status = 1;
                } else {
                    msjPhoto.status = -1;
                }
            msjPhoto.fileUploaded = false;
            msjPhoto.save();
            Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                    .executeSingle();
            if (chat == null) {
                Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.receptor)
                        .executeSingle();
                Chats newChat = new Chats();
                newChat.mensajeId = msjPhoto.mensajeId;
                newChat.idContacto = msjPhoto.receptor;
                newChat.isLockedConversation = false;
                newChat.lastStatus = msjPhoto.status;
                newChat.email = msjPhoto.receptorEmail;
                if (contact != null) {
                    newChat.photo = contact.photo;
                    newChat.fullName = contact.fullName;
                    newChat.lang = contact.lang;
                    newChat.screenName = contact.screenName;
                    newChat.photoload = true;
                    newChat.phone = contact.phone;
                } else {
                    newChat.photo = null;
                    newChat.photoload = false;
                    newChat.fullName = msjPhoto.receptorEmail;
                    newChat.lang = msjPhoto.receptorLang;
                    newChat.screenName = msjPhoto.receptorEmail;
                    newChat.phone = null;
                }
                newChat.emitedAt = msjPhoto.emitedAt;
                newChat.notRead = 0;
                newChat.lastMessage = "send Image";
                newChat.show = true;
                newChat.save();
            } else {
                if (!chat.photoload) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.emisor)
                            .executeSingle();
                    if (contact != null) {
                        chat.photo = contact.photo;
                        chat.photoload = true;
                    } else {
                        chat.photo = null;
                        chat.photoload = false;
                    }
                }
                chat.mensajeId = msjPhoto.mensajeId;
                chat.lastStatus = msjPhoto.status;
                chat.emitedAt = msjPhoto.emitedAt;
                chat.notRead = 0;
                chat.lastMessage = "send Image";
                chat.save();
            }
            showNewMessage(msjPhoto);

        } catch (Exception e) {
        }
        System.gc();
    }
    if (requestCode == 23) {
        if (resultCode == Activity.RESULT_OK) {
            Bitmap bitmapRotate = C
                    .rotateBitmapAndScale(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            System.gc();
            Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
            System.gc();
            Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
            System.gc();
            Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
            System.gc();
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                outputStream.flush();
                outputStream.close();
                System.gc();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                final Message msjPhoto = new Message();
                String id = u.id + contact.idContacto + dateToCamera
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjPhoto.mensajeId = id;
                msjPhoto.emisor = u.id;
                msjPhoto.receptor = contact.idContacto;
                msjPhoto.emisorEmail = u.email;
                msjPhoto.receptorEmail = contact.email;
                msjPhoto.emisorLang = u.lang;
                msjPhoto.receptorLang = contact.lang;
                msjPhoto.emitedAt = dateToCamera;
                msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
                if (tiempoMensaje)
                    msjPhoto.delay = temporizadorSeek.getValue();
                else
                    msjPhoto.delay = 0;
                msjPhoto.photoName = file.getAbsolutePath();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] byteArray = stream.toByteArray();
                msjPhoto.photo = byteArray;

                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                byte[] byteArray2 = stream2.toByteArray();
                msjPhoto.photoBlur = byteArray2;
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        msjPhoto.status = 1;
                    } else {
                        msjPhoto.status = -1;
                    }
                msjPhoto.fileUploaded = false;
                msjPhoto.save();
                Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                        .executeSingle();
                if (chat == null) {
                    Contact contact = new Select().from(Contact.class)
                            .where("id_contact = ?", msjPhoto.receptor).executeSingle();
                    Chats newChat = new Chats();
                    newChat.mensajeId = msjPhoto.mensajeId;
                    newChat.idContacto = msjPhoto.receptor;
                    newChat.isLockedConversation = false;
                    newChat.lastStatus = msjPhoto.status;
                    newChat.email = msjPhoto.receptorEmail;
                    if (contact != null) {
                        newChat.photo = contact.photo;
                        newChat.fullName = contact.fullName;
                        newChat.lang = contact.lang;
                        newChat.screenName = contact.screenName;
                        newChat.photoload = true;
                        newChat.phone = contact.phone;
                    } else {
                        newChat.photo = null;
                        newChat.photoload = false;
                        newChat.fullName = msjPhoto.receptorEmail;
                        newChat.lang = msjPhoto.receptorLang;
                        newChat.screenName = msjPhoto.receptorEmail;
                        newChat.phone = null;
                    }
                    newChat.emitedAt = msjPhoto.emitedAt;
                    newChat.notRead = 0;
                    newChat.lastMessage = "send Image";
                    newChat.show = true;
                    newChat.save();
                } else {
                    if (!chat.photoload) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjPhoto.emisor).executeSingle();
                        if (contact != null) {
                            chat.photo = contact.photo;
                            chat.photoload = true;
                        } else {
                            chat.photo = null;
                            chat.photoload = false;
                        }
                    }
                    chat.mensajeId = msjPhoto.mensajeId;
                    chat.lastStatus = msjPhoto.status;
                    chat.emitedAt = msjPhoto.emitedAt;
                    chat.notRead = 0;
                    chat.lastMessage = "send Image";
                    chat.save();
                }
                showNewMessage(msjPhoto);
            } catch (Exception e) {
            }
            System.gc();
        }
    }
}

From source file:com.xperia64.rompatcher.MainActivity.java

public void patch(final boolean c, final boolean d, final boolean r, final String ed) {
    final ProgressDialog myPd_ring = ProgressDialog.show(MainActivity.this,
            getResources().getString(R.string.wait), getResources().getString(R.string.wait_desc), true);
    myPd_ring.setCancelable(false);/* ww w .j  av  a  2  s .co m*/
    new Thread(new Runnable() {
        public void run() {
            if (new File(Globals.patchToApply).exists() && new File(Globals.fileToPatch).exists()
                    && !Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".ecm")) {
                String msg = getResources().getString(R.string.success);
                if (!new File(Globals.fileToPatch).canWrite()) {
                    Globals.msg = msg = "Can not write to output file. If you are on KitKat or Lollipop, move the file to your internal storage.";
                    return;
                }
                if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ups")) {
                    int e = upsPatchRom(Globals.fileToPatch, Globals.patchToApply, Globals.fileToPatch + ".new",
                            r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_UPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta3")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".vcdiff")) {
                    RandomAccessFile f = null;
                    try {
                        f = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    StringBuilder s = new StringBuilder();
                    try {
                        if (f.length() >= 9) {
                            for (int i = 0; i < 8; i++) {
                                s.append((char) f.readByte());
                                f.seek(i + 1);
                            }
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        f.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    // Header of xdelta patch determines version
                    if (s.toString().equals("%XDELTA%") || s.toString().equals("%XDZ000%")
                            || s.toString().equals("%XDZ001%") || s.toString().equals("%XDZ002%")
                            || s.toString().equals("%XDZ003%") || s.toString().equals("%XDZ004%")) {
                        int e = xdelta1PatchRom(Globals.fileToPatch, Globals.patchToApply,
                                Globals.fileToPatch + ".new");
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_XDELTA1);
                        }
                    } else {
                        int e = xdelta3PatchRom(Globals.fileToPatch, Globals.patchToApply,
                                Globals.fileToPatch + ".new");
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_XDELTA3);
                        }
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bps")) {
                    int e = bpsPatchRom(Globals.fileToPatch, Globals.patchToApply, Globals.fileToPatch + ".new",
                            r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_BPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dps")) {
                    int e = dpsPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_DPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bsdiff")) {
                    int e = bsdiffPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_BSDIFF);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".aps")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // Wow.
                    byte[] gbaSig = { 0x41, 0x50, 0x53, 0x31, 0x00 };
                    byte[] n64Sig = { 0x41, 0x50, 0x53, 0x31, 0x30 };
                    byte[] realSig = new byte[5];
                    RandomAccessFile raf = null;
                    System.out.println("APS Patch");
                    try {
                        raf = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    try {
                        raf.read(realSig);
                        raf.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    if (Arrays.equals(realSig, gbaSig)) {
                        System.out.println("GBA APS");
                        APSGBAPatcher aa = new APSGBAPatcher();
                        aa.crcTableInit();
                        int e = 0;
                        try {
                            e = aa.ApplyPatch(Globals.patchToApply, Globals.fileToPatch, r);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            e = -5;
                        }
                        System.out.println("e: " + e);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_APSGBA);
                        }
                    } else if (Arrays.equals(realSig, n64Sig)) {
                        System.out.println("N64 APS");
                        int e = apsN64PatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_APSN64);
                        }
                    } else {
                        msg = parseError(-131, -10000);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ppf")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e = ppfPatchRom(Globals.fileToPatch, Globals.patchToApply, r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_PPF);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".patch")) {
                    int e = xdelta1PatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_XDELTA1);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".asm")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e;
                    if (Globals.asar)
                        e = asarPatchRom(Globals.fileToPatch, Globals.patchToApply, r ? 1 : 0);
                    else
                        e = asmPatchRom(Globals.fileToPatch, Globals.patchToApply);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_ASM);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dldi")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e = dldiPatchRom(Globals.fileToPatch, Globals.patchToApply);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_DLDI);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xpc")) {
                    int e = xpcPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_XPC);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".nmp")) {

                    String drm = MainActivity.this.getPackageName();
                    System.out.println("Drm is: " + drm);
                    if (drm.equals("com.xperia64.rompatcher.donation")) {
                        if (c) {
                            File f = new File(Globals.fileToPatch);
                            File f2 = new File(Globals.fileToPatch + ".bak");
                            try {
                                Files.copy(f, f2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        NitroROMFilesystem fs;
                        try {
                            fs = new NitroROMFilesystem(Globals.fileToPatch);
                            ROM.load(fs);
                            RealPatch.patch(Globals.patchToApply, new Object());
                            ROM.close();
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            //e1.printStackTrace();
                            Globals.msg = msg = String.format(getResources().getString(R.string.nmpDefault),
                                    e1.getStackTrace()[0].getFileName(), e1.getStackTrace()[0].getLineNumber());
                        }
                        if (c && d && !TextUtils.isEmpty(ed)) {
                            File f = new File(Globals.fileToPatch);
                            File f3 = new File(Globals.fileToPatch + ".bak");
                            File f2 = new File(
                                    Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/') + 1)
                                            + ed);
                            f.renameTo(f2);
                            f3.renameTo(f);
                        }
                    } else {
                        Globals.msg = msg = getResources().getString(R.string.drmwarning);
                        MainActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                                b.setTitle(getResources().getString(R.string.drmwarning));
                                b.setIcon(
                                        ResourcesCompat.getDrawable(getResources(), R.drawable.icon_pro, null));
                                b.setMessage(getResources().getString(R.string.drmwarning_desc));
                                b.setCancelable(false);
                                b.setNegativeButton(getResources().getString(android.R.string.cancel),
                                        new OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                            }
                                        });
                                b.setPositiveButton(getResources().getString(R.string.nagInfo),
                                        new OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                                try {
                                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                                            "market://details?id=com.xperia64.rompatcher.donation")));
                                                } catch (android.content.ActivityNotFoundException anfe) {
                                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                                            "http://play.google.com/store/apps/details?id=com.xperia64.rompatcher.donation")));
                                                }
                                            }
                                        });
                                b.create().show();
                            }
                        });
                    }

                } else {
                    RandomAccessFile f = null;
                    try {
                        f = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    StringBuilder s = new StringBuilder();
                    try {
                        if (f.length() >= 6) {
                            for (int i = 0; i < 5; i++) {
                                s.append((char) f.readByte());
                                f.seek(i + 1);
                            }
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        f.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    int e;
                    // Two variants of IPS, the normal PATCH type, then this weird one called IPS32 with messily hacked in 32 bit offsets
                    if (s.toString().equals("IPS32")) {
                        e = ips32PatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_IPS);
                        }
                    } else {
                        e = ipsPatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_IPS);
                        }
                    }

                }
                if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ups")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta3")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".vcdiff")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".patch")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bps")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bsdiff")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dps")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xpc")) {
                    File oldrom = new File(Globals.fileToPatch);
                    File bkrom = new File(Globals.fileToPatch + ".bak");
                    oldrom.renameTo(bkrom);
                    File newrom = new File(Globals.fileToPatch + ".new");
                    newrom.renameTo(oldrom);
                }
                if (!c) {
                    File f = new File(Globals.fileToPatch + ".bak");
                    if (f.exists()) {
                        f.delete();
                    }
                } else {
                    if (d) {
                        File one = new File(Globals.fileToPatch + ".bak");
                        File two = new File(Globals.fileToPatch);
                        File three = new File(
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/') + 1)
                                        + ed);
                        two.renameTo(three);
                        File four = new File(Globals.fileToPatch);
                        one.renameTo(four);
                    }
                }
                Globals.msg = msg;
            } else if (Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".ecm")) {
                int e = 0;
                String msg = getResources().getString(R.string.success);
                if (c) {

                    if (d) {
                        e = ecmPatchRom(Globals.fileToPatch,
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/')) + ed, 1);
                    } else {
                        //new File(Globals.fileToPatch).renameTo(new File(Globals.fileToPatch+".bak"));
                        e = ecmPatchRom(Globals.fileToPatch,
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('.')), 1);
                    }
                } else {
                    e = ecmPatchRom(Globals.fileToPatch, "", 0);
                }
                if (e != 0) {
                    msg = parseError(e, Globals.TYPE_ECM);
                }
                Globals.msg = msg;
            } else {
                Globals.msg = getResources().getString(R.string.fnf);
            }

        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (Globals.msg.equals("")) {
                    Thread.sleep(25);
                }
                ;
                myPd_ring.dismiss();
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast t = Toast.makeText(staticThis, Globals.msg, Toast.LENGTH_SHORT);
                        t.show();
                        Globals.msg = "";
                    }
                });
                if (Globals.msg.equals(getResources().getString(R.string.success))) // Don't annoy people who did something wrong even further
                {
                    final SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(MainActivity.this);
                    int x = prefs.getInt("purchaseNag", 5);
                    if (x != -1) {
                        if ((isPackageInstalled("com.xperia64.timidityae", MainActivity.this)
                                || isPackageInstalled("com.xperia64.rompatcher.donation", MainActivity.this))) {
                            prefs.edit().putInt("purchaseNag", -1);
                        } else {
                            if (x >= 5) {

                                prefs.edit().putInt("purchaseNag", 0).commit();
                                /*runOnUiThread(new Runnable() {
                                    public void run() {
                                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                                b.setTitle("Like ROM Patcher?");
                                b.setIcon(getResources().getDrawable(R.drawable.icon_pro));
                                b.setMessage(getResources().getString(R.string.nagMsg));
                                b.setCancelable(false);
                                b.setNegativeButton(getResources().getString(android.R.string.cancel), new OnClickListener(){@Override public void onClick(DialogInterface arg0, int arg1) {}});
                                b.setPositiveButton(getResources().getString(R.string.nagInfo), new OnClickListener(){
                                        
                                  @Override
                                  public void onClick(DialogInterface arg0, int arg1) {
                                     try  {
                                         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.xperia64.rompatcher.donation")));
                                     } catch (android.content.ActivityNotFoundException anfe) {
                                         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.xperia64.rompatcher.donation")));
                                     }
                                  }
                                   });
                                      b.create().show();
                                       }
                                   }); // end of UIThread*/
                            } else {
                                prefs.edit().putInt("purchaseNag", x + 1).commit();
                            }
                        }
                    }
                }

            } catch (Exception e) {
            }
        }
    }).start();
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override//  w ww . j  av a 2 s .  c  om
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(SonetCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Sonet.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            SonetOAuth sonetOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Sonet.getPackageIntent(
                                            SonetCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Sonet.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mSonetCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_BODY, "",
                                            mMessage.getText().toString())));
                                    httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPost));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG))
                                .show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else
            (Toast.makeText(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override//from   w ww .j  a v a  2s  . c o m
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(MyfeedleCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Myfeedle.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            MyfeedleOAuth myfeedleOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Myfeedle.getPackageIntent(
                                            MyfeedleCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Myfeedle.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mMyfeedleCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                            myfeedleOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mMyfeedleCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_BODY, "",
                                            mMessage.getText().toString())));
                                    httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                            myfeedleOAuth.getSignedRequest(httpPost));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(MyfeedleCreatePost.this, params[0] + " " + params[1],
                                Toast.LENGTH_LONG)).show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else
            (Toast.makeText(MyfeedleCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:com.piusvelte.sonet.SonetCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override/*  w w w.  j  a v  a  2  s .  c om*/
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(SonetCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Sonet.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            SonetOAuth sonetOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Sonet.getPackageIntent(
                                            SonetCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Sonet.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mSonetCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                        BuildConfig.LINKEDIN_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_BODY, "",
                                            mMessage.getText().toString())));
                                    httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPost));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                        BuildConfig.IDENTICA_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(String.format(
                                        CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG))
                                .show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else
            (Toast.makeText(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:com.piusvelte.sonet.core.SonetComments.java

private void loadComments() {
    mComments.clear();/*from   w w w .ja v  a  2 s  .c  o m*/
    setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
            new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) },
            new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
    mMessage.setEnabled(false);
    mMessage.setText(R.string.loading);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
        @Override
        protected String doInBackground(Void... none) {
            // load the status itself
            if (mData != null) {
                SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
                UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
                String authority = Sonet.getAuthority(SonetComments.this);
                um.addURI(authority, SonetProvider.VIEW_STATUSES_STYLES + "/*", SonetProvider.STATUSES_STYLES);
                um.addURI(authority, SonetProvider.TABLE_NOTIFICATIONS + "/*", SonetProvider.NOTIFICATIONS);
                Cursor status;
                switch (um.match(mData)) {
                case SonetProvider.STATUSES_STYLES:
                    status = getContentResolver().query(Statuses_styles.getContentUri(SonetComments.this),
                            new String[] { Statuses_styles.ACCOUNT, Statuses_styles.SID, Statuses_styles.ESID,
                                    Statuses_styles.WIDGET, Statuses_styles.SERVICE, Statuses_styles.FRIEND,
                                    Statuses_styles.MESSAGE, Statuses_styles.CREATED },
                            Statuses_styles._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (status.moveToFirst()) {
                        mService = status.getInt(4);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                        mAccount = status.getLong(0);
                        mSid = sonetCrypto.Decrypt(status.getString(1));
                        mEsid = sonetCrypto.Decrypt(status.getString(2));
                        Cursor widget = getContentResolver().query(
                                Widgets_settings.getContentUri(SonetComments.this),
                                new String[] { Widgets.TIME24HR },
                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                new String[] { Integer.toString(status.getInt(3)), Long.toString(mAccount) },
                                null);
                        if (widget.moveToFirst()) {
                            mTime24hr = widget.getInt(0) == 1;
                        } else {
                            Cursor b = getContentResolver().query(
                                    Widgets_settings.getContentUri(SonetComments.this),
                                    new String[] { Widgets.TIME24HR },
                                    Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                    new String[] { Integer.toString(status.getInt(3)),
                                            Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                    null);
                            if (b.moveToFirst()) {
                                mTime24hr = b.getInt(0) == 1;
                            } else {
                                Cursor c = getContentResolver()
                                        .query(Widgets_settings.getContentUri(SonetComments.this),
                                                new String[] { Widgets.TIME24HR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                if (c.moveToFirst()) {
                                    mTime24hr = c.getInt(0) == 1;
                                } else {
                                    mTime24hr = false;
                                }
                                c.close();
                            }
                            b.close();
                        }
                        widget.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, status.getString(5));
                        commentMap.put(Statuses.MESSAGE, status.getString(6));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(status.getLong(7), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet)
                                        : mService == IDENTICA ? getString(R.string.repeat) : "");
                        mComments.add(commentMap);
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                        }
                        account.close();
                    }
                    status.close();
                    break;
                case SonetProvider.NOTIFICATIONS:
                    Cursor notification = getContentResolver().query(
                            Notifications.getContentUri(SonetComments.this),
                            new String[] { Notifications.ACCOUNT, Notifications.SID, Notifications.ESID,
                                    Notifications.FRIEND, Notifications.MESSAGE, Notifications.CREATED },
                            Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (notification.moveToFirst()) {
                        // clear notification
                        ContentValues values = new ContentValues();
                        values.put(Notifications.CLEARED, 1);
                        getContentResolver().update(Notifications.getContentUri(SonetComments.this), values,
                                Notifications._ID + "=?", new String[] { mData.getLastPathSegment() });
                        mAccount = notification.getLong(0);
                        mSid = sonetCrypto.Decrypt(notification.getString(1));
                        mEsid = sonetCrypto.Decrypt(notification.getString(2));
                        mTime24hr = false;
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID,
                                        Accounts.SERVICE },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                            mService = account.getInt(3);
                        }
                        account.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, notification.getString(3));
                        commentMap.put(Statuses.MESSAGE, notification.getString(4));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(notification.getLong(5), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet) : getString(R.string.repeat));
                        mComments.add(commentMap);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                    }
                    notification.close();
                    break;
                default:
                    mComments.clear();
                    HashMap<String, String> commentMap = new HashMap<String, String>();
                    commentMap.put(Statuses.SID, "");
                    commentMap.put(Entities.FRIEND, "");
                    commentMap.put(Statuses.MESSAGE, "error, status not found");
                    commentMap.put(Statuses.CREATEDTEXT, "");
                    commentMap.put(getString(R.string.like), "");
                    mComments.add(commentMap);
                }
                String response = null;
                HttpGet httpGet;
                SonetOAuth sonetOAuth;
                boolean liked = false;
                String screen_name = "";
                switch (mService) {
                case TWITTER:
                    sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(TWITTER_MENTIONS,
                                    TWITTER_BASE_URL, String.format(TWITTER_SINCE_ID, mSid)))));
                    break;
                case FACEBOOK:
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            new HttpGet(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, mSid, Saccess_token,
                                    mToken)))) != null) {
                        try {
                            JSONArray likes = new JSONObject(response).getJSONArray(Sdata);
                            for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                JSONObject like = likes.getJSONObject(i);
                                if (like.getString(Sid).equals(mAccountSid)) {
                                    liked = true;
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(getString(liked ? R.string.unlike : R.string.like));
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)));
                    break;
                case MYSPACE:
                    sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String
                                    .format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid))));
                    break;
                case LINKEDIN:
                    sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret);
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(httpGet))) != null) {
                        try {
                            JSONObject data = new JSONObject(response);
                            if (data.has("isCommentable") && !data.getBoolean("isCommentable")) {
                                publishProgress(getString(R.string.uncommentable));
                            }
                            if (data.has("isLikable")) {
                                publishProgress(getString(
                                        data.has("isLiked") && data.getBoolean("isLiked") ? R.string.unlike
                                                : R.string.like));
                            } else {
                                publishProgress(getString(R.string.unlikable));
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        publishProgress(getString(R.string.unlikable));
                    }
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet));
                    break;
                case FOURSQUARE:
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, mSid, mToken)));
                    break;
                case IDENTICA:
                    sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(IDENTICA_MENTIONS,
                                    IDENTICA_BASE_URL, String.format(IDENTICA_SINCE_ID, mSid)))));
                    break;
                case GOOGLEPLUS:
                    //TODO:
                    // get plussed status
                    break;
                case CHATTER:
                    // Chatter requires loading an instance
                    if ((mChatterInstance == null) || (mChatterToken == null)) {
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(
                                String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mToken)))) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                    mChatterInstance = jobj.getString("instance_url");
                                    mChatterToken = jobj.getString(Saccess_token);
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    if ((mChatterInstance != null) && (mChatterToken != null)) {
                        httpGet = new HttpGet(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, httpGet)) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.getInt(Stotal) > 0) {
                                    JSONArray likes = jobj.getJSONArray("likes");
                                    for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                        JSONObject like = likes.getJSONObject(i);
                                        if (like.getJSONObject(Suser).getString(Sid).equals(mAccountSid)) {
                                            mChatterLikeId = like.getString(Sid);
                                            liked = true;
                                            break;
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        publishProgress(getString(liked ? R.string.unlike : R.string.like));
                        httpGet = new HttpGet(String.format(CHATTER_URL_COMMENTS, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpGet);
                    } else {
                        response = null;
                    }
                    break;
                }
                return response;
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... params) {
            mMessage.setText("");
            if (params != null) {
                if ((mService == TWITTER) || (mService == IDENTICA)) {
                    mMessage.append(params[0]);
                } else {
                    if (mService == LINKEDIN) {
                        if (params[0].equals(getString(R.string.uncommentable))) {
                            mSend.setEnabled(false);
                            mMessage.setEnabled(false);
                            mMessage.setText(R.string.uncommentable);
                        } else {
                            setCommentStatus(0, params[0]);
                        }
                    } else {
                        setCommentStatus(0, params[0]);
                    }
                }
            }
            mMessage.setEnabled(true);
        }

        @Override
        protected void onPostExecute(String response) {
            if (response != null) {
                int i2;
                try {
                    JSONArray comments;
                    mSimpleDateFormat = null;
                    switch (mService) {
                    case TWITTER:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.retweet));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case FACEBOOK:
                        comments = new JSONObject(response).getJSONArray(Sdata);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND, comment.getJSONObject(Sfrom).getString(Sname));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Smessage));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(Screated_time) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like),
                                        getString(comment.has(Suser_likes) && comment.getBoolean(Suser_likes)
                                                ? R.string.unlike
                                                : R.string.like));
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case MYSPACE:
                        comments = new JSONObject(response).getJSONArray(Sentry);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject entry = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, entry.getString(ScommentId));
                                commentMap.put(Entities.FRIEND,
                                        entry.getJSONObject(Sauthor).getString(SdisplayName));
                                commentMap.put(Statuses.MESSAGE, entry.getString(Sbody));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(
                                                parseDate(entry.getString(SpostedDate), MYSPACE_DATE_FORMAT),
                                                mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case LINKEDIN:
                        JSONObject jsonResponse = new JSONObject(response);
                        if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) {
                            comments = jsonResponse.getJSONArray(Svalues);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    JSONObject person = comment.getJSONObject(Sperson);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            person.getString(SfirstName) + " " + person.getString(SlastName));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Scomment));
                                    commentMap.put(Statuses.CREATEDTEXT,
                                            Sonet.getCreatedText(comment.getLong(Stimestamp), mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        }
                        break;
                    case FOURSQUARE:
                        comments = new JSONObject(response).getJSONObject(Sresponse).getJSONObject(Scheckin)
                                .getJSONObject(Scomments).getJSONArray(Sitems);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                JSONObject user = comment.getJSONObject(Suser);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND,
                                        user.getString(SfirstName) + " " + user.getString(SlastName));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(ScreatedAt) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case IDENTICA:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.repeat));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case GOOGLEPLUS:
                        //TODO: load comments
                        HttpPost httpPost = new HttpPost(GOOGLE_ACCESS);
                        List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
                        httpParams.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID));
                        httpParams.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET));
                        httpParams.add(new BasicNameValuePair("refresh_token", mToken));
                        httpParams.add(new BasicNameValuePair("grant_type", "refresh_token"));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(httpParams));
                            if ((response = SonetHttpClient.httpResponse(mHttpClient, httpPost)) != null) {
                                JSONObject j = new JSONObject(response);
                                if (j.has(Saccess_token)) {
                                    String access_token = j.getString(Saccess_token);
                                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                                            new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL,
                                                    mSid, access_token)))) != null) {
                                        // check for a newer post, if it's the user's own, then set CLEARED=0
                                        try {
                                            JSONObject item = new JSONObject(response);
                                            if (item.has(Sobject)) {
                                                JSONObject object = item.getJSONObject(Sobject);
                                                if (object.has(Sreplies)) {
                                                    int commentCount = 0;
                                                    JSONObject replies = object.getJSONObject(Sreplies);
                                                    if (replies.has(StotalItems)) {
                                                        //TODO: load comments
                                                        commentCount = replies.getInt(StotalItems);
                                                    }
                                                }
                                            }
                                        } catch (JSONException e) {
                                            Log.e(TAG, e.toString());
                                        }
                                    }
                                }
                            }
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case CHATTER:
                        JSONObject chats = new JSONObject(response);
                        if (chats.getInt(Stotal) > 0) {
                            comments = chats.getJSONArray(Scomments);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE,
                                            comment.getJSONObject(Sbody).getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(ScreatedDate), CHATTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        } else {
                            noComments();
                        }
                        break;
                    }
                } catch (JSONException e) {
                    Log.e(TAG, e.toString());
                }
            } else {
                noComments();
            }
            setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
                    new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT,
                            getString(R.string.like) },
                    new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }

        private void noComments() {
            HashMap<String, String> commentMap = new HashMap<String, String>();
            commentMap.put(Statuses.SID, "");
            commentMap.put(Entities.FRIEND, "");
            commentMap.put(Statuses.MESSAGE, getString(R.string.no_comments));
            commentMap.put(Statuses.CREATEDTEXT, "");
            commentMap.put(getString(R.string.like), "");
            mComments.add(commentMap);
        }

        private long parseDate(String date, String format) {
            if (date != null) {
                // hack for the literal 'Z'
                if (date.substring(date.length() - 1).equals("Z")) {
                    date = date.substring(0, date.length() - 2) + "+0000";
                }
                Date created = null;
                if (format != null) {
                    if (mSimpleDateFormat == null) {
                        mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
                        // all dates should be GMT/UTC
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                    }
                    try {
                        created = mSimpleDateFormat.parse(date);
                        return created.getTime();
                    } catch (ParseException e) {
                        Log.e(TAG, e.toString());
                    }
                } else {
                    // attempt to parse RSS date
                    if (mSimpleDateFormat != null) {
                        try {
                            created = mSimpleDateFormat.parse(date);
                            return created.getTime();
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    for (String rfc822 : sRFC822) {
                        mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH);
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                        try {
                            if ((created = mSimpleDateFormat.parse(date)) != null) {
                                return created.getTime();
                            }
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                }
            }
            return System.currentTimeMillis();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute();
}

From source file:com.piusvelte.sonet.SonetComments.java

private void loadComments() {
    mComments.clear();//from ww  w  .  j a  va 2  s.  c o m
    setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
            new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) },
            new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
    mMessage.setEnabled(false);
    mMessage.setText(R.string.loading);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
        @Override
        protected String doInBackground(Void... none) {
            // load the status itself
            if (mData != null) {
                SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
                UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
                String authority = Sonet.getAuthority(SonetComments.this);
                um.addURI(authority, SonetProvider.VIEW_STATUSES_STYLES + "/*", SonetProvider.STATUSES_STYLES);
                um.addURI(authority, SonetProvider.TABLE_NOTIFICATIONS + "/*", SonetProvider.NOTIFICATIONS);
                Cursor status;
                switch (um.match(mData)) {
                case SonetProvider.STATUSES_STYLES:
                    status = getContentResolver().query(Statuses_styles.getContentUri(SonetComments.this),
                            new String[] { Statuses_styles.ACCOUNT, Statuses_styles.SID, Statuses_styles.ESID,
                                    Statuses_styles.WIDGET, Statuses_styles.SERVICE, Statuses_styles.FRIEND,
                                    Statuses_styles.MESSAGE, Statuses_styles.CREATED },
                            Statuses_styles._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (status.moveToFirst()) {
                        mService = status.getInt(4);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                        mAccount = status.getLong(0);
                        mSid = sonetCrypto.Decrypt(status.getString(1));
                        mEsid = sonetCrypto.Decrypt(status.getString(2));
                        Cursor widget = getContentResolver().query(
                                Widgets_settings.getContentUri(SonetComments.this),
                                new String[] { Widgets.TIME24HR },
                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                new String[] { Integer.toString(status.getInt(3)), Long.toString(mAccount) },
                                null);
                        if (widget.moveToFirst()) {
                            mTime24hr = widget.getInt(0) == 1;
                        } else {
                            Cursor b = getContentResolver().query(
                                    Widgets_settings.getContentUri(SonetComments.this),
                                    new String[] { Widgets.TIME24HR },
                                    Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                    new String[] { Integer.toString(status.getInt(3)),
                                            Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                    null);
                            if (b.moveToFirst()) {
                                mTime24hr = b.getInt(0) == 1;
                            } else {
                                Cursor c = getContentResolver()
                                        .query(Widgets_settings.getContentUri(SonetComments.this),
                                                new String[] { Widgets.TIME24HR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                if (c.moveToFirst()) {
                                    mTime24hr = c.getInt(0) == 1;
                                } else {
                                    mTime24hr = false;
                                }
                                c.close();
                            }
                            b.close();
                        }
                        widget.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, status.getString(5));
                        commentMap.put(Statuses.MESSAGE, status.getString(6));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(status.getLong(7), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet)
                                        : mService == IDENTICA ? getString(R.string.repeat) : "");
                        mComments.add(commentMap);
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                        }
                        account.close();
                    }
                    status.close();
                    break;
                case SonetProvider.NOTIFICATIONS:
                    Cursor notification = getContentResolver().query(
                            Notifications.getContentUri(SonetComments.this),
                            new String[] { Notifications.ACCOUNT, Notifications.SID, Notifications.ESID,
                                    Notifications.FRIEND, Notifications.MESSAGE, Notifications.CREATED },
                            Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }, null);
                    if (notification.moveToFirst()) {
                        // clear notification
                        ContentValues values = new ContentValues();
                        values.put(Notifications.CLEARED, 1);
                        getContentResolver().update(Notifications.getContentUri(SonetComments.this), values,
                                Notifications._ID + "=?", new String[] { mData.getLastPathSegment() });
                        mAccount = notification.getLong(0);
                        mSid = sonetCrypto.Decrypt(notification.getString(1));
                        mEsid = sonetCrypto.Decrypt(notification.getString(2));
                        mTime24hr = false;
                        // load the session
                        Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this),
                                new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID,
                                        Accounts.SERVICE },
                                Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null);
                        if (account.moveToFirst()) {
                            mToken = sonetCrypto.Decrypt(account.getString(0));
                            mSecret = sonetCrypto.Decrypt(account.getString(1));
                            mAccountSid = sonetCrypto.Decrypt(account.getString(2));
                            mService = account.getInt(3);
                        }
                        account.close();
                        HashMap<String, String> commentMap = new HashMap<String, String>();
                        commentMap.put(Statuses.SID, mSid);
                        commentMap.put(Entities.FRIEND, notification.getString(3));
                        commentMap.put(Statuses.MESSAGE, notification.getString(4));
                        commentMap.put(Statuses.CREATEDTEXT,
                                Sonet.getCreatedText(notification.getLong(5), mTime24hr));
                        commentMap.put(getString(R.string.like),
                                mService == TWITTER ? getString(R.string.retweet) : getString(R.string.repeat));
                        mComments.add(commentMap);
                        mServiceName = getResources().getStringArray(R.array.service_entries)[mService];
                    }
                    notification.close();
                    break;
                default:
                    mComments.clear();
                    HashMap<String, String> commentMap = new HashMap<String, String>();
                    commentMap.put(Statuses.SID, "");
                    commentMap.put(Entities.FRIEND, "");
                    commentMap.put(Statuses.MESSAGE, "error, status not found");
                    commentMap.put(Statuses.CREATEDTEXT, "");
                    commentMap.put(getString(R.string.like), "");
                    mComments.add(commentMap);
                }
                String response = null;
                HttpGet httpGet;
                SonetOAuth sonetOAuth;
                boolean liked = false;
                String screen_name = "";
                switch (mService) {
                case TWITTER:
                    sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken,
                            mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(TWITTER_MENTIONS,
                                    TWITTER_BASE_URL, String.format(TWITTER_SINCE_ID, mSid)))));
                    break;
                case FACEBOOK:
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            new HttpGet(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, mSid, Saccess_token,
                                    mToken)))) != null) {
                        try {
                            JSONArray likes = new JSONObject(response).getJSONArray(Sdata);
                            for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                JSONObject like = likes.getJSONObject(i);
                                if (like.getString(Sid).equals(mAccountSid)) {
                                    liked = true;
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(getString(liked ? R.string.unlike : R.string.like));
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)));
                    break;
                case MYSPACE:
                    sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken,
                            mSecret);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String
                                    .format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid))));
                    break;
                case LINKEDIN:
                    sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, mToken,
                            mSecret);
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(httpGet))) != null) {
                        try {
                            JSONObject data = new JSONObject(response);
                            if (data.has("isCommentable") && !data.getBoolean("isCommentable")) {
                                publishProgress(getString(R.string.uncommentable));
                            }
                            if (data.has("isLikable")) {
                                publishProgress(getString(
                                        data.has("isLiked") && data.getBoolean("isLiked") ? R.string.unlike
                                                : R.string.like));
                            } else {
                                publishProgress(getString(R.string.unlikable));
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        publishProgress(getString(R.string.unlikable));
                    }
                    httpGet = new HttpGet(String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                    for (String[] header : LINKEDIN_HEADERS)
                        httpGet.setHeader(header[0], header[1]);
                    response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet));
                    break;
                case FOURSQUARE:
                    response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, mSid, mToken)));
                    break;
                case IDENTICA:
                    sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, mToken,
                            mSecret);
                    if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))))) != null) {
                        try {
                            JSONObject user = new JSONObject(response);
                            screen_name = "@" + user.getString(Sscreen_name) + " ";
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    publishProgress(screen_name);
                    response = SonetHttpClient.httpResponse(mHttpClient,
                            sonetOAuth.getSignedRequest(new HttpGet(String.format(IDENTICA_MENTIONS,
                                    IDENTICA_BASE_URL, String.format(IDENTICA_SINCE_ID, mSid)))));
                    break;
                case GOOGLEPLUS:
                    //TODO:
                    // get plussed status
                    break;
                case CHATTER:
                    // Chatter requires loading an instance
                    if ((mChatterInstance == null) || (mChatterToken == null)) {
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(
                                String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mToken)))) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                    mChatterInstance = jobj.getString("instance_url");
                                    mChatterToken = jobj.getString(Saccess_token);
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    if ((mChatterInstance != null) && (mChatterToken != null)) {
                        httpGet = new HttpGet(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        if ((response = SonetHttpClient.httpResponse(mHttpClient, httpGet)) != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.getInt(Stotal) > 0) {
                                    JSONArray likes = jobj.getJSONArray("likes");
                                    for (int i = 0, i2 = likes.length(); i < i2; i++) {
                                        JSONObject like = likes.getJSONObject(i);
                                        if (like.getJSONObject(Suser).getString(Sid).equals(mAccountSid)) {
                                            mChatterLikeId = like.getString(Sid);
                                            liked = true;
                                            break;
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        publishProgress(getString(liked ? R.string.unlike : R.string.like));
                        httpGet = new HttpGet(String.format(CHATTER_URL_COMMENTS, mChatterInstance, mSid));
                        httpGet.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpGet);
                    } else {
                        response = null;
                    }
                    break;
                }
                return response;
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... params) {
            mMessage.setText("");
            if (params != null) {
                if ((mService == TWITTER) || (mService == IDENTICA)) {
                    mMessage.append(params[0]);
                } else {
                    if (mService == LINKEDIN) {
                        if (params[0].equals(getString(R.string.uncommentable))) {
                            mSend.setEnabled(false);
                            mMessage.setEnabled(false);
                            mMessage.setText(R.string.uncommentable);
                        } else {
                            setCommentStatus(0, params[0]);
                        }
                    } else {
                        setCommentStatus(0, params[0]);
                    }
                }
            }
            mMessage.setEnabled(true);
        }

        @Override
        protected void onPostExecute(String response) {
            if (response != null) {
                int i2;
                try {
                    JSONArray comments;
                    mSimpleDateFormat = null;
                    switch (mService) {
                    case TWITTER:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.retweet));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case FACEBOOK:
                        comments = new JSONObject(response).getJSONArray(Sdata);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND, comment.getJSONObject(Sfrom).getString(Sname));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Smessage));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(Screated_time) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like),
                                        getString(comment.has(Suser_likes) && comment.getBoolean(Suser_likes)
                                                ? R.string.unlike
                                                : R.string.like));
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case MYSPACE:
                        comments = new JSONObject(response).getJSONArray(Sentry);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject entry = comments.getJSONObject(i);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, entry.getString(ScommentId));
                                commentMap.put(Entities.FRIEND,
                                        entry.getJSONObject(Sauthor).getString(SdisplayName));
                                commentMap.put(Statuses.MESSAGE, entry.getString(Sbody));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(
                                                parseDate(entry.getString(SpostedDate), MYSPACE_DATE_FORMAT),
                                                mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case LINKEDIN:
                        JSONObject jsonResponse = new JSONObject(response);
                        if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) {
                            comments = jsonResponse.getJSONArray(Svalues);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    JSONObject person = comment.getJSONObject(Sperson);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            person.getString(SfirstName) + " " + person.getString(SlastName));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Scomment));
                                    commentMap.put(Statuses.CREATEDTEXT,
                                            Sonet.getCreatedText(comment.getLong(Stimestamp), mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        }
                        break;
                    case FOURSQUARE:
                        comments = new JSONObject(response).getJSONObject(Sresponse).getJSONObject(Scheckin)
                                .getJSONObject(Scomments).getJSONArray(Sitems);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                JSONObject user = comment.getJSONObject(Suser);
                                HashMap<String, String> commentMap = new HashMap<String, String>();
                                commentMap.put(Statuses.SID, comment.getString(Sid));
                                commentMap.put(Entities.FRIEND,
                                        user.getString(SfirstName) + " " + user.getString(SlastName));
                                commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                commentMap.put(Statuses.CREATEDTEXT,
                                        Sonet.getCreatedText(comment.getLong(ScreatedAt) * 1000, mTime24hr));
                                commentMap.put(getString(R.string.like), "");
                                mComments.add(commentMap);
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case IDENTICA:
                        comments = new JSONArray(response);
                        if ((i2 = comments.length()) > 0) {
                            for (int i = 0; i < i2; i++) {
                                JSONObject comment = comments.getJSONObject(i);
                                if (comment.getString(Sin_reply_to_status_id) == mSid) {
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE, comment.getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), getString(R.string.repeat));
                                    mComments.add(commentMap);
                                }
                            }
                        } else {
                            noComments();
                        }
                        break;
                    case GOOGLEPLUS:
                        //TODO: load comments
                        HttpPost httpPost = new HttpPost(GOOGLE_ACCESS);
                        List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
                        httpParams.add(new BasicNameValuePair("client_id", BuildConfig.GOOGLECLIENT_ID));
                        httpParams
                                .add(new BasicNameValuePair("client_secret", BuildConfig.GOOGLECLIENT_SECRET));
                        httpParams.add(new BasicNameValuePair("refresh_token", mToken));
                        httpParams.add(new BasicNameValuePair("grant_type", "refresh_token"));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(httpParams));
                            if ((response = SonetHttpClient.httpResponse(mHttpClient, httpPost)) != null) {
                                JSONObject j = new JSONObject(response);
                                if (j.has(Saccess_token)) {
                                    String access_token = j.getString(Saccess_token);
                                    if ((response = SonetHttpClient.httpResponse(mHttpClient,
                                            new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL,
                                                    mSid, access_token)))) != null) {
                                        // check for a newer post, if it's the user's own, then set CLEARED=0
                                        try {
                                            JSONObject item = new JSONObject(response);
                                            if (item.has(Sobject)) {
                                                JSONObject object = item.getJSONObject(Sobject);
                                                if (object.has(Sreplies)) {
                                                    int commentCount = 0;
                                                    JSONObject replies = object.getJSONObject(Sreplies);
                                                    if (replies.has(StotalItems)) {
                                                        //TODO: load comments
                                                        commentCount = replies.getInt(StotalItems);
                                                    }
                                                }
                                            }
                                        } catch (JSONException e) {
                                            Log.e(TAG, e.toString());
                                        }
                                    }
                                }
                            }
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case CHATTER:
                        JSONObject chats = new JSONObject(response);
                        if (chats.getInt(Stotal) > 0) {
                            comments = chats.getJSONArray(Scomments);
                            if ((i2 = comments.length()) > 0) {
                                for (int i = 0; i < i2; i++) {
                                    JSONObject comment = comments.getJSONObject(i);
                                    HashMap<String, String> commentMap = new HashMap<String, String>();
                                    commentMap.put(Statuses.SID, comment.getString(Sid));
                                    commentMap.put(Entities.FRIEND,
                                            comment.getJSONObject(Suser).getString(Sname));
                                    commentMap.put(Statuses.MESSAGE,
                                            comment.getJSONObject(Sbody).getString(Stext));
                                    commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(
                                            parseDate(comment.getString(ScreatedDate), CHATTER_DATE_FORMAT),
                                            mTime24hr));
                                    commentMap.put(getString(R.string.like), "");
                                    mComments.add(commentMap);
                                }
                            } else {
                                noComments();
                            }
                        } else {
                            noComments();
                        }
                        break;
                    }
                } catch (JSONException e) {
                    Log.e(TAG, e.toString());
                }
            } else {
                noComments();
            }
            setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment,
                    new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT,
                            getString(R.string.like) },
                    new int[] { R.id.friend, R.id.message, R.id.created, R.id.like }));
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }

        private void noComments() {
            HashMap<String, String> commentMap = new HashMap<String, String>();
            commentMap.put(Statuses.SID, "");
            commentMap.put(Entities.FRIEND, "");
            commentMap.put(Statuses.MESSAGE, getString(R.string.no_comments));
            commentMap.put(Statuses.CREATEDTEXT, "");
            commentMap.put(getString(R.string.like), "");
            mComments.add(commentMap);
        }

        private long parseDate(String date, String format) {
            if (date != null) {
                // hack for the literal 'Z'
                if (date.substring(date.length() - 1).equals("Z")) {
                    date = date.substring(0, date.length() - 2) + "+0000";
                }
                Date created = null;
                if (format != null) {
                    if (mSimpleDateFormat == null) {
                        mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
                        // all dates should be GMT/UTC
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                    }
                    try {
                        created = mSimpleDateFormat.parse(date);
                        return created.getTime();
                    } catch (ParseException e) {
                        Log.e(TAG, e.toString());
                    }
                } else {
                    // attempt to parse RSS date
                    if (mSimpleDateFormat != null) {
                        try {
                            created = mSimpleDateFormat.parse(date);
                            return created.getTime();
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                    for (String rfc822 : sRFC822) {
                        mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH);
                        mSimpleDateFormat.setTimeZone(sTimeZone);
                        try {
                            if ((created = mSimpleDateFormat.parse(date)) != null) {
                                return created.getTime();
                            }
                        } catch (ParseException e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                }
            }
            return System.currentTimeMillis();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute();
}