Example usage for android.widget SimpleAdapter SimpleAdapter

List of usage examples for android.widget SimpleAdapter SimpleAdapter

Introduction

In this page you can find the example usage for android.widget SimpleAdapter SimpleAdapter.

Prototype

public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, @LayoutRes int resource,
        String[] from, @IdRes int[] to) 

Source Link

Document

Constructor

Usage

From source file:com.abeo.tia.noordin.ProcesscaseLoanSubsidiary.java

public void dropdownKIV() throws JSONException {
    RequestParams params = null;//from w  ww  . j  a  v  a  2 s.  c  o m
    params = new RequestParams();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("TableName", "OCRD");
    jsonObject.put("FieldName", "KIVSTATUS");
    params.put("sJsonInput", jsonObject.toString());

    RestService.post(GET_SPINNER_VALUES, params, new BaseJsonHttpResponseHandler<String>() {

        @Override
        public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) {
            // TODO Auto-generated method stub
            System.out.println(arg3);
            System.out.println("Failed");

        }

        @Override
        protected String parseResponse(String s, boolean b) throws Throwable {
            return null;
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) {
            // TODO Auto-generated method stub
            System.out.println("Title Dropdown Success Details ");
            System.out.println(arg2);

            try {

                arrayResponse = new JSONArray(arg2);
                // Create new list
                jsonArraylist = new ArrayList<HashMap<String, String>>();

                for (int i = 0; i < arrayResponse.length(); i++) {

                    jsonResponse = arrayResponse.getJSONObject(i);

                    id = jsonResponse.getString("Id").toString();
                    name = jsonResponse.getString("Name").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> proList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON  LIST");
                    proList.put("Id_T", id);
                    System.out.println(name);
                    proList.put("Name_T", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON PROPERTY LIST");

                    jsonArraylist.add(proList);
                    System.out.println("JSON PROPERTY LIST");
                    System.out.println(jsonArraylist);
                }
                // Spinner set Array Data in Drop down

                sAdapPROJ = new SimpleAdapter(ProcesscaseLoanSubsidiary.this, jsonArraylist,
                        R.layout.spinner_item, new String[] { "Id_T", "Name_T" },
                        new int[] { R.id.Id, R.id.Name });

                spinner_kiv.setAdapter(sAdapPROJ);

                for (int j = 0; j < jsonArraylist.size(); j++) {
                    if (jsonArraylist.get(j).get("Id_T").equals(Skiv)) {
                        spinner_kiv.setSelection(j);
                        break;
                    }
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
    });
}

From source file:com.abeo.tia.noordin.ProcessCaseLoanPrincipal.java

public void dropdownstatus() throws JSONException {
    RequestParams params = null;/*from w  ww  .j av  a 2s .c  om*/
    params = new RequestParams();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("TableName", "OCRD");
    jsonObject.put("FieldName", "CASESTATUS");
    params.put("sJsonInput", jsonObject.toString());

    RestService.post(GET_SPINNER_VALUES, params, new BaseJsonHttpResponseHandler<String>() {

        @Override
        public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) {
            // TODO Auto-generated method stub
            System.out.println(arg3);
            System.out.println("Failed");

        }

        @Override
        protected String parseResponse(String s, boolean b) throws Throwable {
            return null;
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) {
            // TODO Auto-generated method stub
            System.out.println("Title Dropdown Success Details ");
            System.out.println(arg2);

            try {

                arrayResponse = new JSONArray(arg2);
                // Create new list
                jsonArraylist = new ArrayList<HashMap<String, String>>();

                for (int i = 0; i < arrayResponse.length(); i++) {

                    jsonResponse = arrayResponse.getJSONObject(i);

                    id = jsonResponse.getString("Id").toString();
                    name = jsonResponse.getString("Name").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> proList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON  LIST");
                    proList.put("Id_T", id);
                    System.out.println(name);
                    proList.put("Name_T", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON PROPERTY LIST");

                    jsonArraylist.add(proList);
                    System.out.println("JSON PROPERTY LIST");
                    System.out.println(jsonArraylist);
                }
                // Spinner set Array Data in Drop down

                sAdapPROJ = new SimpleAdapter(ProcessCaseLoanPrincipal.this, jsonArraylist,
                        R.layout.spinner_item, new String[] { "Id_T", "Name_T" },
                        new int[] { R.id.Id, R.id.Name });

                spinner_case_status.setAdapter(sAdapPROJ);

                for (int j = 0; j < jsonArraylist.size(); j++) {
                    if (jsonArraylist.get(j).get("Id_T").equals(Scase_status)) {
                        spinner_case_status.setSelection(j);
                        break;
                    }
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
    });
}

From source file:com.abeo.tia.noordin.AddCaseStep2of4.java

public void dropdownBankDeveloperSolicitor() {

    RequestParams params = null;/* w  w  w. ja v  a2  s .  co  m*/
    params = new RequestParams();

    RestService.post(METHOD_PROPERTY_BDS_DROPDOWN, params, new BaseJsonHttpResponseHandler<String>() {

        @Override
        public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) {
            // TODO Auto-generated method stub
            System.out.println(arg3);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) {
            // TODO Auto-generated method stub
            System.out.println("Property Activity GetDropdown Success Details ");
            try {
                // Create new list
                jsonlistBank = new ArrayList<HashMap<String, String>>();
                jsonlistDeveloper = new ArrayList<HashMap<String, String>>();
                jsonlistSolicitor = new ArrayList<HashMap<String, String>>();

                jsonResponse = new JSONObject(arg2);

                JSONArray jsonBank = jsonResponse.getJSONArray("Bank");
                for (int j = 0; j < jsonBank.length(); j++) {
                    JSONObject bank = jsonBank.getJSONObject(j);

                    id_b = bank.getString("BankCode").toString();
                    name_b = bank.getString("BankName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> bankList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON BANK LIST");
                    bankList.put("Id_T", id_b);
                    System.out.println(name);
                    bankList.put("Name_T", name_b);
                    System.out.println(name);
                    System.out.println(" END SEND JSON BANK LIST");

                    jsonlistBank.add(bankList);
                    System.out.println("JSON BANK LIST");
                    System.out.println(jsonlistProject);

                }

                // Spinner set Array Data in Drop down

                sAdapBANK = new SimpleAdapter(AddCaseStep2of4.this, jsonlistBank, R.layout.spinner_item,
                        new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyLSTCHG_BANKNAME.setAdapter(sAdapBANK);

                for (int j = 0; j < jsonlistBank.size(); j++) {
                    if (jsonlistBank.get(j).get("Name_T").equals(bankDetailResponse)) {
                        spinnerpropertyLSTCHG_BANKNAME.setSelection(j);
                        break;
                    }
                }

                JSONArray jsonDeveloper = jsonResponse.getJSONArray("Developer");
                for (int j = 0; j < jsonDeveloper.length(); j++) {
                    JSONObject dev = jsonDeveloper.getJSONObject(j);
                    id = dev.getString("DevCode").toString();
                    name = dev.getString("DevName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> devList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON DEV LIST");
                    devList.put("Id_B", id);
                    System.out.println(name);
                    devList.put("Name_B", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON DEV LIST");

                    jsonlistDeveloper.add(devList);
                    System.out.println("JSON DEV LIST");
                    System.out.println(jsonlistDeveloper);

                }
                // Spinner set Array Data in Drop down

                sAdapDEV = new SimpleAdapter(AddCaseStep2of4.this, jsonlistDeveloper, R.layout.spinner_item,
                        new String[] { "Id_B", "Name_B" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyDEVELOPER.setAdapter(sAdapDEV);

                for (int j = 0; j < jsonlistDeveloper.size(); j++) {
                    if (jsonlistDeveloper.get(j).get("Id_B").equals(developerCodeResponse)) {
                        spinnerpropertyDEVELOPER.setSelection(j);
                        break;
                    }
                }

                JSONArray jsonSolicitor = jsonResponse.getJSONArray("Solicitor");
                for (int j = 0; j < jsonSolicitor.length(); j++) {
                    JSONObject solic = jsonSolicitor.getJSONObject(j);
                    id = solic.getString("SoliCode").toString();
                    name = solic.getString("SoliName").toString();

                    // SEND JSON DATA INTO SPINNER TITLE LIST
                    HashMap<String, String> solicList = new HashMap<String, String>();

                    // Send JSON Data to list activity
                    System.out.println("SEND JSON SOLICITOR LIST");
                    solicList.put("Id_T", id);
                    System.out.println(name);
                    solicList.put("Name_T", name);
                    System.out.println(name);
                    System.out.println(" END SEND JSON SOLICITOR LIST");

                    jsonlistSolicitor.add(solicList);
                    System.out.println("JSON SOLICITOR LIST");
                    System.out.println(jsonlistSolicitor);
                }

                // Spinner set Array Data in Drop down
                sAdapSOLIC = new SimpleAdapter(AddCaseStep2of4.this, jsonlistSolicitor, R.layout.spinner_item,
                        new String[] { "Id_T", "Name_T" }, new int[] { R.id.Id, R.id.Name });

                spinnerpropertyDEVSOLICTOR.setAdapter(sAdapSOLIC);

                for (int j = 0; j < jsonlistSolicitor.size(); j++) {
                    if (jsonlistSolicitor.get(j).get("Id_T").equals(devSolictorCodeResponse)) {
                        spinnerpropertyDEVSOLICTOR.setSelection(j);
                        break;
                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println(arg2);

        }

        @Override
        protected String parseResponse(String arg0, boolean arg1) throws Throwable {
            // Get Json response

            System.out.println("Property GetDropdown parse Response");
            System.out.println(arg0);
            return null;
        }

    });

}

From source file:smart.services.fragment.AddCar.java

@SuppressLint("InlinedApi")
@SuppressWarnings("deprecation")
public void showInsuranceDialog() {
    dialog.setContentView(R.layout.add_car_dialog);
    dialog.setCancelable(true);/*from w  ww  .  ja va  2 s.  c  o m*/
    dialog.setTitle("Choose an Insurance company");

    TextView dialogTitleTV = (TextView) dialog.findViewById(R.id.brandsListTitleTV);

    Booking.changeWidthHeight(getActivity(), dialog);
    // dialog.setP
    lv = (ListView) dialog.findViewById(R.id.addLV);
    swipeView = (SwipeRefreshLayout) dialog.findViewById(R.id.swipeDialog);
    if (dataBaseHandler.getInsuranceCount() == 0) {
        if (carFunctions.isConnectingToInternet()) {
            new InsuranceAsyncTask().execute();
        } else {
            Toast.makeText(getActivity(), "Check your internet connection", Toast.LENGTH_LONG).show();
        }
    } else {
        insuracneCompanyList.clear();
        ArrayList<Insurance> insuranceArrayList = dataBaseHandler.getAllInsurance();
        for (int i = 0; i < insuranceArrayList.size(); i++) {
            HashMap<String, String> insurance = new HashMap<String, String>();
            insurance.put("id", insuranceArrayList.get(i).getId() + "");
            insurance.put("nameAr", insuranceArrayList.get(i).getNameAr());
            insurance.put("nameEn", insuranceArrayList.get(i).getNameEn());

            insuracneCompanyList.add(insurance);
        }

        ListAdapter adapter = null;

        if (setting.getDuration() == 0) {
            dialog.findViewById(R.id.titleIVAr).setVisibility(View.GONE);
            dialogTitleTV.setText(getResources().getString(R.string.company_list_en));

            adapter = new SimpleAdapter(getActivity(), insuracneCompanyList, R.layout.single_insurance_item,
                    new String[] { "id", "nameEn" }, new int[] { R.id.insuranceId, R.id.nameEn });
        } else {
            dialog.findViewById(R.id.titleIVEn).setVisibility(View.GONE);
            dialogTitleTV.setText(getResources().getString(R.string.company_list_ar));

            adapter = new SimpleAdapter(getActivity(), insuracneCompanyList, R.layout.single_insurance_item,
                    new String[] { "id", "nameAr" }, new int[] { R.id.insuranceId, R.id.nameEn });
        }

        lv.setAdapter(adapter);

        swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeView.setRefreshing(true);
                if (carFunctions.isConnectingToInternet()) {
                    new InsuranceAsyncTask().execute();
                } else {
                    Toast.makeText(getActivity(), "Check your internet connection", Toast.LENGTH_LONG).show();
                }
            }
        });
        swipeView.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String nameEn = ((TextView) view.findViewById(R.id.nameEn)).getText().toString();
                String idC = ((TextView) view.findViewById(R.id.insuranceId)).getText().toString();
                insuranceTV.setText(nameEn);
                insuranceIdTV.setText(idC);
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

From source file:com.hichinaschool.flashcards.anki.CardEditor.java

private StyledDialog createDialogIntentInformation(Builder builder, Resources res) {
    builder.setTitle(res.getString(R.string.intent_add_saved_information));
    ListView listView = new ListView(this);

    mIntentInformationAdapter = new SimpleAdapter(this, mIntentInformation, R.layout.card_item,
            new String[] { "source", "target", "id" },
            new int[] { R.id.card_sfld, R.id.card_tmpl, R.id.card_item });
    listView.setAdapter(mIntentInformationAdapter);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override//  ww  w.j av  a 2s.co  m
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(CardEditor.this, CardEditor.class);
            intent.putExtra(EXTRA_CALLER, CALLER_CARDEDITOR_INTENT_ADD);
            HashMap<String, String> map = mIntentInformation.get(position);
            intent.putExtra(EXTRA_CONTENTS, map.get("fields"));
            intent.putExtra(EXTRA_ID, map.get("id"));
            startActivityForResult(intent, REQUEST_INTENT_ADD);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(CardEditor.this, ActivityTransitionAnimation.FADE);
            }
            mIntentInformationDialog.dismiss();
        }
    });
    mCardItemBackground = Themes.getCardBrowserBackground()[0];
    mIntentInformationAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object arg1, String text) {
            if (view.getId() == R.id.card_item) {
                view.setBackgroundResource(mCardItemBackground);
                return true;
            }
            return false;
        }
    });
    listView.setBackgroundColor(android.R.attr.colorBackground);
    listView.setDrawSelectorOnTop(true);
    listView.setFastScrollEnabled(true);
    Themes.setContentStyle(listView, Themes.CALLER_CARDEDITOR_INTENTDIALOG);
    builder.setView(listView, false, true);
    builder.setCancelable(true);
    builder.setPositiveButton(res.getString(R.string.intent_add_clear_all), new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int arg1) {
            MetaDB.resetIntentInformation(CardEditor.this);
            mIntentInformation.clear();
            dialog.dismiss();
        }
    });
    StyledDialog dialog = builder.create();
    mIntentInformationDialog = dialog;
    return dialog;
}

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

private void setCommentStatus(int position, String status) {
    if (mComments.size() > position) {
        HashMap<String, String> comment = mComments.get(position);
        comment.put(getString(R.string.like), status);
        mComments.set(position, comment);
        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 }));
    }/*from www  .  ja v  a2  s. c  om*/
}

From source file:com.abeo.tia.noordin.PropertyActivity.java

public void dropdownPorjectTitleType() {
    // Passing value in JSON format in first 8-fields

    /* { "TableName": "@AE_PROPERTY", "FieldName": "TITLETYPE" } */
    JSONObject jsonObject = new JSONObject();

    try {/* w w  w . ja va 2  s.c  om*/
        jsonObject.put("TableName", "@AE_PROPERTY");
        jsonObject.put("FieldName", "TITLETYPE");

        RequestParams params = new RequestParams();
        params.put("sJsonInput", jsonObject.toString());
        System.out.println(params);

        RestService.post(METHOD_PROPERTY_TITLETYPE_LIST_DROPDOWN, params,
                new BaseJsonHttpResponseHandler<String>() {

                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, String arg4) {
                        // TODO Auto-generated method stub
                        System.out.println(arg3);

                    }

                    @Override
                    public void onSuccess(int arg0, Header[] arg1, String arg2, String arg3) {
                        // TODO Auto-generated method stub
                        System.out.println("propertyTitle Type Dropdown Success Details ");
                        System.out.println(arg2);

                        try {

                            arrayResponse = new JSONArray(arg2);
                            // Create new list
                            jsonlistProjectTitle = new ArrayList<HashMap<String, String>>();

                            for (int i = 0; i < arrayResponse.length(); i++) {

                                jsonResponse = arrayResponse.getJSONObject(i);

                                id = jsonResponse.getString("Id").toString();
                                name = jsonResponse.getString("Name").toString();

                                // SEND JSON DATA INTO SPINNER TITLE LIST
                                HashMap<String, String> proList = new HashMap<String, String>();

                                // Send JSON Data to list activity
                                System.out.println("SEND JSON TITLE TYPE LIST");
                                proList.put("Id_T", id);
                                System.out.println(name);
                                proList.put("Name_T", name);
                                System.out.println(name);
                                System.out.println(" END SEND JSON PROPERTY TITLE TYPE LIST");

                                jsonlistProjectTitle.add(proList);
                                System.out.println("JSON PROPERTY LIST");
                                System.out.println(jsonlistProjectTitle);
                            }
                            // Spinner set Array Data in Drop down

                            sAdapTYPE = new SimpleAdapter(PropertyActivity.this, jsonlistProjectTitle,
                                    R.layout.spinner_item, new String[] { "Id_T", "Name_T" },
                                    new int[] { R.id.Id, R.id.Name });

                            spinnerpropertyTitleType.setAdapter(sAdapTYPE);

                            for (int j = 0; j < jsonlistProjectTitle.size(); j++) {
                                if (jsonlistProjectTitle.get(j).get("Name_T").equals(titleTypeDetailResponse)) {
                                    spinnerpropertyTitleType.setSelection(j);
                                    break;
                                }
                            }

                        } catch (JSONException e) { // TODO Auto-generated
                            // catc
                            // block
                            e.printStackTrace();
                        }

                    }

                    @Override
                    protected String parseResponse(String arg0, boolean arg1) throws Throwable {

                        // Get Json response
                        arrayResponse = new JSONArray(arg0);
                        jsonResponse = arrayResponse.getJSONObject(0);

                        System.out.println("Property Title Type Dropdown Details parse Response");
                        System.out.println(arg0);
                        return null;
                    }
                });
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:com.ichi2.anki2.DeckPicker.java

/** Called when the activity is first created. */
@Override/*from   w  ww .  j a  v a2s .  c  o m*/
protected void onCreate(Bundle savedInstanceState) throws SQLException {
    Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate");
    Intent intent = getIntent();
    if (!isTaskRoot()) {
        Log.i(AnkiDroidApp.TAG,
                "DeckPicker - onCreate: Detected multiple instance of this activity, closing it and return to root activity");
        Intent reloadIntent = new Intent(DeckPicker.this, DeckPicker.class);
        reloadIntent.setAction(Intent.ACTION_MAIN);
        if (intent != null && intent.getExtras() != null) {
            reloadIntent.putExtras(intent.getExtras());
        }
        if (intent != null && intent.getData() != null) {
            reloadIntent.setData(intent.getData());
        }
        reloadIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
        startActivityIfNeeded(reloadIntent, 0);
    }
    if (intent.getData() != null) {
        mImportPath = getIntent().getData().getEncodedPath();
    }

    // need to start this here in order to avoid showing deckpicker before splashscreen
    if (AnkiDroidApp.colIsOpen()) {
        setTitle(getResources().getString(R.string.app_name));
    } else {
        setTitle("");
        mOpenCollectionHandler.onPreExecute();
    }

    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    // mStartedByBigWidget = intent.getIntExtra(EXTRA_START, EXTRA_START_NOTHING);

    SharedPreferences preferences = restorePreferences();

    // activate broadcast messages if first start of a day
    if (mLastTimeOpened < UIUtils.getDayStart()) {
        preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
    }
    preferences.edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();

    // if (intent != null && intent.hasExtra(EXTRA_DECK_ID)) {
    // openStudyOptions(intent.getLongExtra(EXTRA_DECK_ID, 1));
    // }

    BroadcastMessages.checkForNewMessages(this);

    View mainView = getLayoutInflater().inflate(R.layout.deck_picker, null);
    setContentView(mainView);

    // check, if tablet layout
    View studyoptionsFrame = findViewById(R.id.studyoptions_fragment);
    mFragmented = studyoptionsFrame != null && studyoptionsFrame.getVisibility() == View.VISIBLE;

    Themes.setContentStyle(mFragmented ? mainView : mainView.findViewById(R.id.deckpicker_view),
            Themes.CALLER_DECKPICKER);

    registerExternalStorageListener();

    if (!mFragmented) {
        mAddButton = (ImageButton) findViewById(R.id.deckpicker_add);
        mAddButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addNote();
            }
        });

        mCardsButton = (ImageButton) findViewById(R.id.deckpicker_card_browser);
        mCardsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openCardBrowser();
            }
        });

        mStatsButton = (ImageButton) findViewById(R.id.statistics_all_button);
        mStatsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DIALOG_SELECT_STATISTICS_TYPE);
            }
        });

        mSyncButton = (ImageButton) findViewById(R.id.sync_all_button);
        mSyncButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sync();
            }
        });
    }

    mInvalidateMenu = false;
    mDeckList = new ArrayList<HashMap<String, String>>();
    mDeckListView = (ListView) findViewById(R.id.files);
    mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item,
            new String[] { "name", "new", "lrn", "rev", // "complMat", "complAll",
                    "sep", "dyn" },
            new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn, R.id.deckpicker_rev, // R.id.deckpicker_bar_mat, R.id.deckpicker_bar_all,
                    R.id.deckpicker_deck, R.id.DeckPickerName });
    mDeckListAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object data, String text) {
            if (view.getId() == R.id.deckpicker_deck) {
                if (text.equals("top")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_top);
                    return true;
                } else if (text.equals("bot")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_bottom);
                    return true;
                } else if (text.equals("ful")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_full);
                    return true;
                } else if (text.equals("cen")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_center);
                    return true;
                }
            } else if (view.getId() == R.id.DeckPickerName) {
                if (text.equals("d0")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.non_dyn_deck));
                    return true;
                } else if (text.equals("d1")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.dyn_deck));
                    return true;
                }
            }
            // } else if (view.getId() == R.id.deckpicker_bar_mat || view.getId() == R.id.deckpicker_bar_all) {
            // if (text.length() > 0 && !text.equals("-1.0")) {
            // View parent = (View)view.getParent().getParent();
            // if (text.equals("-2")) {
            // parent.setVisibility(View.GONE);
            // } else {
            // Utils.updateProgressBars(view, (int) UIUtils.getDensityAdjustedValue(DeckPicker.this, 3.4f),
            // (int) (Double.parseDouble(text) * ((View)view.getParent().getParent().getParent()).getHeight()));
            // if (parent.getVisibility() == View.INVISIBLE) {
            // parent.setVisibility(View.VISIBLE);
            // parent.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // }
            // }
            // }
            // return true;
            // } else if (view.getVisibility() == View.INVISIBLE) {
            // if (!text.equals("-1")) {
            // view.setVisibility(View.VISIBLE);
            // view.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // return false;
            // }
            // } else if (text.equals("-1")){
            // view.setVisibility(View.INVISIBLE);
            // return false;
            return false;
        }
    });
    mDeckListView.setOnItemClickListener(mDeckSelHandler);
    mDeckListView.setAdapter(mDeckListAdapter);

    if (mFragmented) {
        mDeckListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    registerForContextMenu(mDeckListView);

    showStartupScreensAndDialogs(preferences, 0);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        mDeckListView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
    }
}

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

private void loadComments() {
    mComments.clear();/*w w w.jav a  2 s. c  om*/
    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   www  . j av  a  2  s.co  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();
}