Example usage for android.os StrictMode setThreadPolicy

List of usage examples for android.os StrictMode setThreadPolicy

Introduction

In this page you can find the example usage for android.os StrictMode setThreadPolicy.

Prototype

public static void setThreadPolicy(final ThreadPolicy policy) 

Source Link

Document

Sets the policy for what actions on the current thread should be detected, as well as the penalty if such actions occur.

Usage

From source file:com.sourcey.materiallogindemo.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Permission StrictMode
    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }/*from w ww.j  a v  a2s. c om*/

    Bundle extras = getIntent().getExtras();
    // ?? null
    if (extras != null) {
        user_id = extras.getString("user_id");
        name = extras.getString("name");
        image = extras.getString("image");
    }

    txtStart = (AutoCompleteTextView) findViewById(R.id.txtStart);
    txtEnd = (AutoCompleteTextView) findViewById(R.id.txtEnd);
    txtAppoint = (AutoCompleteTextView) findViewById(R.id.txtAppoint);
    txtTime = (EditText) findViewById(R.id.txtTime);
    txtLicensePlate = (EditText) findViewById(R.id.txtLicensePlate);
    btnImageProfile = (ImageButton) findViewById(R.id.btnImageProfile);
    txtName = (TextView) findViewById(R.id.txtName);

    radioGroup = (RadioGroup) findViewById(R.id.radio);

    badge = (TextView) findViewById(R.id.badge);

    final Button btnSave = (Button) findViewById(R.id.btnSave);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);
    //final Button btnPost = (Button) findViewById(R.id.btnPost);
    final Button btnFeed = (Button) findViewById(R.id.btnFeed);
    final Button btnSearch = (Button) findViewById(R.id.btnSearch);
    final Button btnNotification = (Button) findViewById(R.id.btnNotification);
    final Button btnLogout = (Button) findViewById(R.id.btnLogout);
    final Button btnTime = (Button) findViewById(R.id.btnTime);
    final Button btnComment = (Button) findViewById(R.id.btnComment);
    // get the current time
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    mHour = c.get(Calendar.HOUR);
    mMinute = c.get(Calendar.MINUTE);

    String url = getString(R.string.url) + "notification.php";
    notifications = master.GetCountNotification(user_id, url);
    if (notifications > 0) {
        badge.setVisibility(View.VISIBLE);
        badge.setText(String.valueOf(notifications));
    } else {
        badge.setVisibility(View.GONE);
    }

    // display the current time
    updateCurrentTime();
    LoadItems();
    //Create adapter
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item);
    txtStart.setThreshold(1);
    //Set adapter to AutoCompleteTextView
    txtStart.setAdapter(adapter);
    txtStart.setOnItemSelectedListener(this);
    txtStart.setOnItemClickListener(this);

    //Set adapter to AutoCompleteTextView
    txtEnd.setAdapter(adapter);
    txtEnd.setOnItemSelectedListener(this);
    txtEnd.setOnItemClickListener(this);
    //Create adapter

    //Set adapter to AutoCompleteTextView
    txtAppoint.setAdapter(adapter);
    txtAppoint.setOnItemSelectedListener(this);
    txtAppoint.setOnItemClickListener(this);

    txtName.setText(name);
    String photo_url_str = getString(R.string.url_image)
            + (("".equals(image.trim()) || image == null) ? "no.png" : image.trim());
    URL newurl = null;
    try {
        newurl = new URL(photo_url_str);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    Bitmap b = null;
    try {
        b = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    btnImageProfile.setImageBitmap(Bitmap.createScaledBitmap(b, 80, 80, false));

    btnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogMap();
        }
    });

    btnTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(TIME_DIALOG_ID);
        }
    });
    btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            type = ((RadioButton) findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
            if ("".equals(type)) {
                type = "CAR";
            } else {
                type = "NOCAR";
            }
            /* Toast.makeText(getBaseContext(),
                type, Toast.LENGTH_SHORT).show();*/

            start = txtStart.getText().toString();
            end = txtEnd.getText().toString();
            meeting_point = txtAppoint.getText().toString();
            map_datetime = datePoint.trim();
            license_plate = txtLicensePlate.getText().toString();

            if ("".equals(start) || "".equals(end) || "".equals(meeting_point) || "".equals(map_datetime)
                    || "".equals(license_plate) || "".equals(txtTime.getText().toString().trim())) {
                MessageDialog("???");
            } else {
                String url = getString(R.string.url) + "save.php";
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id", user_id));
                params.add(new BasicNameValuePair("start", start));
                params.add(new BasicNameValuePair("end", end));
                params.add(new BasicNameValuePair("meeting_point", meeting_point));
                params.add(new BasicNameValuePair("map_datetime", map_datetime));
                params.add(new BasicNameValuePair("license_plate", license_plate));
                params.add(new BasicNameValuePair("type", type));

                String resultServer = getHttpPost(url, params);

                JSONObject c;
                try {
                    c = new JSONObject(resultServer);
                    String status = c.getString("status");
                    MessageDialog(status);
                    if ("?".equals(status)) {
                        ClearData();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    MessageDialog(e.getMessage());
                }
            }
        }
    });

    btnCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ClearData();
        }
    });

    /*        btnPost.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       *//* Intent i = new Intent(getBaseContext(), PostItemActivity.class);
          i.putExtra("user_id", user_id);
          startActivity(i);*//*
                              // get selected radio button from radioGroup
                                      
                              }
                              });*/

    btnFeed.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            /*  if(!start.getText().toString().equals("") &&!end.getText().toString().equals("")&&
                !point.getText().toString().equals("")&&!time.getText().toString().equals("")&&!license.getText().toString().equals("")) {
            Intent newActivity = new Intent(MainActivity.this, commit.class);
            startActivity(newActivity);
              }*/
            Intent i = new Intent(getBaseContext(), PostItemActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnNotification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), NotificationActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), LoginActivity.class);
            startActivity(i);
        }
    });
    btnComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), CommentActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    /*      final Button btn5 = (Button) findViewById(R.id.button3);
          btn5.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
    }
          });*/

    //RadioGroup car = (RadioGroup) this.findViewById ( R.id.textView18 );

    // car.check(R.id.radioButton);
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    //client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.example.georg.theupub.ProfileActivity.java

public boolean getPoints() {
    Connection conn = null;//ww w  .j  a va 2s  .co  m
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String dbURL = "jdbc:jtds:sqlserver://apollo.in.cs.ucy.ac.cy:1433";
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        return false;
    }
    Properties properties = new Properties();
    properties.put("user", "upub");
    properties.put("password", "XuZ3drup");
    properties.put("databaseName", "upub");
    try {
        conn = DriverManager.getConnection(dbURL, properties);
    } catch (SQLException e) {
        return false;
    }
    String SQL = "Select * From [dbo].[User] where ID='" + sample_user + "'";
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
    } catch (SQLException e) {
        return false;
    }
    ResultSet rs = null;
    try {
        rs = stmt.executeQuery(SQL);
    } catch (SQLException e) {
        return false;
    }
    try {
        if (rs.next()) {
            System.out.print(rs.getInt(7));
            userPoints = rs.getInt(7);
        }
    } catch (SQLException e) {
        return false;
    }
    return true;
}

From source file:com.glm.trainer.NewMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (mConnection == null)
        mConnection = new TrainerServiceConnection(this);
    if (false) {//  www  .j ava2s. c om
        StrictMode.setThreadPolicy(
                new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems
                        .penaltyLog().build());
        StrictMode.setVmPolicy(
                new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects() //or .detectAll() for all detectable problems
                        .penaltyLog().penaltyDeath().build());
    }

    setContentView(R.layout.activity_new_main);

    oSummary = new SummaryFragment();
    oWorkout = new WorkoutFragment();
    oStore = new StoreFragment();
    oAbout = new AboutFragment();

    Rate.app_launched(this);
    super.onCreate(savedInstanceState);
}

From source file:com.isol.app.tracker.Utilita.java

public static JSONArray getJSONArray(String parms) {
    try {//w  w  w . j a v a  2 s. c o  m

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        String res = getHttpData(Constants.serviceURL + parms);
        return new JSONArray(res);
    } catch (Exception ex) {
        return null;
    }

}

From source file:com.alivenet.dmvtaxi.fragment.FragmentArriveDriver.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {

        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);//from w  w w . j  av  a2s  . c o m

    }
    try {
        view = inflater.inflate(R.layout.fragment_time_estemet, container, false);
    } catch (InflateException e) {
    }
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    mPref = getActivity().getSharedPreferences(MYPREF, Context.MODE_PRIVATE);
    mUserId = mPref.getString("userId", null);

    gps = new GPSTracker(getActivity());
    MyApplication.arrivedrivermarker = true;
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Please wait...");
    progressDialog.setCancelable(false);

    mlinerlayoutbottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
    mphone = (ImageView) view.findViewById(R.id.iv_phone);
    mphonenumber = (TextView) view.findViewById(R.id.tv_phonenumber);
    marrivaltime = (TextView) view.findViewById(R.id.tv_textarrival);
    mname = (TextView) view.findViewById(R.id.tv_name);
    mlicence = (TextView) view.findViewById(R.id.tv_licence);
    mtaximodel = (TextView) view.findViewById(R.id.tv_model);
    muserImage = (ImageView) view.findViewById(R.id.imageView_close);
    getLatLong();
    btnSplite = (Button) view.findViewById(R.id.btn_splite_rides);

    btnSplite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(getActivity(), SplitAddFrnd.class);
            startActivity(in);
        }
    });

    mphone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String uri = "tel:" + mphonenumber.getText().toString().trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });

    System.out.println("userId>>>>>>>>>>>>>>>>>>>>>" + mUserId);

    mname.setText(MyApplication.driverName);
    mlicence.setText(MyApplication.licenseId);
    mtaximodel.setText(MyApplication.vehicle);
    mphonenumber.setText(MyApplication.mobileNO);

    Picasso.with(getActivity()).load(MyApplication.imageUrl).error(R.mipmap.avtar).placeholder(R.mipmap.avtar)
            .into(muserImage);

    System.out.println("driverImageurl" + "chceck=" + MyApplication.imageUrl);

    mphonenumber.setText("Call To" + " " + MyApplication.driverName);

    final SinchClient sinchClient = Sinch.getSinchClientBuilder().context(getActivity()).userId(mUserId)
            .applicationKey("3b013f09-db1f-422e-ac7b-c6498e119612")
            .applicationSecret("LMhelEFYtUqms55VX1C7MQ==").environmentHost("sandbox.sinch.com").build();

    sinchClient.setSupportCalling(true);
    sinchClient.start();
    mphone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (call == null) {
                if (MyApplication.mobileNO != null && !MyApplication.mobileNO.equals("")) {
                    call = sinchClient.getCallClient().callPhoneNumber("+" + MyApplication.mobileNO);
                    System.out.println("mobile_number" + MyApplication.mobileNO);
                    //call = sinchClient.getCallClient().callPhoneNumber("+918510834641");
                    try {
                        call.addCallListener(new SinchCallListener());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mphonenumber.setText("Hang Up");
                }
            } else {
                call.hangup();
            }
        }
    });

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                // handle back button's click listener

                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    Fragment homeFragment = new FragmentMainScreen();
                    FragmentManager frgManager;
                    frgManager = getFragmentManager();
                    frgManager.beginTransaction().replace(R.id.fragment_switch, homeFragment).commit();

                    return true;
                }

                return true;
            }
            return false;
        }
    });

    return view;
}

From source file:ca.ualberta.cmput301f12t05.ufill.Webservicer.java

/**
 * Consumes the GET operation of the service
 * /* w  ww  .j  a va2  s. co m*/
 * @return Bin object given the id idP
 * @throws Exception
 */
public CrowdSourcerBin getBin(String SourcerId) throws Exception {

    CrowdSourcerBin responseBin = null;
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("action", "get"));
    nvps.add(new BasicNameValuePair("id", SourcerId));

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    HttpResponse response = httpclient.execute(httpPost);

    String status = response.getStatusLine().toString();
    HttpEntity entity = response.getEntity();

    System.out.println(status);

    if (entity != null) {
        InputStream is = entity.getContent();
        String jsonStringVersion = convertStreamToString(is);
        Type BinType = CrowdSourcerBin.class;
        responseBin = gson.fromJson(jsonStringVersion, BinType);
    }
    entity.consumeContent();
    return responseBin;

}

From source file:com.racoon.ampdroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    controller = Controller.getInstance(getResources().getStringArray(R.array.menu_array));
    mNavItems = getResources().getStringArray(R.array.menu_array);
    mDrawerTitle = getResources().getString(R.string.app_name);
    mTitle = controller.getFragmentsNames()[0];

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setTitle(mTitle);/*from  ww  w. ja  va2s.com*/

    mProgress = (ProgressBar) findViewById(R.id.load_progressbar);
    mProgress.setVisibility(ProgressBar.GONE);
    loadingText = (TextView) findViewById(R.id.load_progressbar_text);
    loadingText.setVisibility(TextView.GONE);
    progressLinearLayout = (LinearLayout) findViewById(R.id.progressbar_layout);
    progressLinearLayout.setVisibility(LinearLayout.GONE);
    contentFrame = (FrameLayout) findViewById(R.id.content_frame);

    /** Media Control **/
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    /** Connection established **/
    if (controller.getServerConfig(this) != null
            && controller.getServer().isConnected(controller.isOnline(getApplicationContext()))) {
        Log.d("bug", controller.getServer().getAmpacheConnection().getAuth());
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[0]),
                controller.getFragmentsNames()[0]);
        activeFragment = 0;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        showToast(getResources().getString(R.string.toastServerConnected), Toast.LENGTH_LONG);
        controller.loadCachedFiles();
        /** Sync Files **/
        synchronize(false);

    } else if (controller.getServerConfig(this) != null
            && !controller.getServer().isConnected(controller.isOnline(getApplicationContext()))) {
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[5]),
                controller.getFragmentsNames()[5]);
        activeFragment = 5;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        mTitle = controller.getFragmentsNames()[5];
        getActionBar().setTitle(mTitle);
        showToast(getResources().getString(R.string.toastServerConnectionRefused), Toast.LENGTH_LONG);
    } else {
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[5]),
                controller.getFragmentsNames()[5]);
        activeFragment = 5;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        mTitle = controller.getFragmentsNames()[5];
        getActionBar().setTitle(mTitle);
        showToast(getResources().getString(R.string.toastSettingsNotSet), Toast.LENGTH_LONG);
    }

    // just styling option add shadow the right edge of the drawer
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely open state. */
        @Override
        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    // Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mNavItems));
    // Set the list's click listener
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
            FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
            tx.replace(R.id.content_frame,
                    Fragment.instantiate(MainActivity.this, controller.getFragments()[pos]),
                    controller.getFragmentsNames()[pos]);
            activeFragment = pos;
            // tx.addToBackStack(null);
            clearBackStack();
            tx.commit();
            mTitle = controller.getFragmentsNames()[pos];
            getActionBar().setTitle(controller.getFragmentsNames()[pos]);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    });
    handleIntent(getIntent());
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

public static <T extends ImageBaseModel> String multiPart(String url, T imageUpload, Long equipmentId,
        Long userId, Long equipmentHistoryId, LocationDTOInterface locationDTOLib) throws IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String result = "";
    if (imageUpload != null) {
        File file = new File(((ImageUploadModel) imageUpload).getRealUri());
        String imageType = getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase();
        String imageName = ConstantImage.IMAGE_NAME;
        Gson gson = new Gson();
        String json = gson.toJson(locationDTOLib);
        mpEntity = addParamsForUpload(file, imageType, imageName, equipmentId, userId, json,
                equipmentHistoryId);//  w w w. j av a  2s.  c  o  m

        httppost.setEntity(mpEntity);
        HttpResponse response;
        response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = GalleryUtils.convertStreamToString(instream);
            instream.close();
        }
    }
    return result;
    //        if (imageUploads != null && imageUploads.size() != 0)
    //        {
    ////            for (T imageUpload : imageUploads)
    ////            {
    ////                File file = new File(((ImageUploadModel) imageUpload).getRealUri());
    ////                mpEntity.addPart(ConstantImage.IMAGE_FILE + imageUploads.indexOf(imageUpload), new FileBody(file));
    ////                mpEntity.addPart(ConstantImage.IMAGE_TYPE + imageUploads.indexOf(imageUpload), new StringBody(getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase()));
    ////                mpEntity.addPart(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload), new StringBody(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload)));
    ////            }
    ////            mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString()));
    ////            mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString()));
    ////            LocationDTOLib locationDTOLib = new LocationDTOLib();
    ////            locationDTOLib.setLatitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setLongitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setStreet("Street");
    ////            Gson gson = new Gson();
    ////            String json = gson.toJson(locationDTOLib);
    ////            mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(json));
    ////        }
    ////        httppost.setEntity(mpEntity);
    ////        HttpResponse response;
    ////        response = httpclient.execute(httppost);
    ////        HttpEntity entity = response.getEntity();
    ////        String result = "";
    ////        if (entity != null)
    ////        {
    ////            InputStream instream = entity.getContent();
    ////            result = GalleryUtils.convertStreamToString(instream);
    ////            instream.close();
    ////        }
    //
}

From source file:com.team08storyapp.ESHelper.java

/**
 * Adds or updates a story on the webservice. The method checks the Story
 * object passed in to see if it contains a onlineStoryId. If it does not it
 * finds the next possible Id to assigned to it and then adds the Story to
 * the webservice with that Id. If the Story object contains an
 * onlineStoryId then it calls the webservice with that Id and the story
 * object, updating the Story that was located at that Id.
 * //from w  w  w.  ja  v  a  2s . c o m
 * @param story
 *            The Story that is being added or updated to the webservice.
 * @return The onlineStoryId of the Story that was added or updated.
 * @see Story
 */
public int addOrUpdateOnlineStory(Story story) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpPost httpPost;
    /*
     * check if there is an online story Id to determine if adding or
     * updating the story
     */
    if (story.getOnlineStoryId() == 0) {
        /*
         * find out how many stories are stored online in order to generate
         * an appropriate online story Id
         */
        ArrayList<Story> stories = getOnlineStories();
        int nextId = stories.size() + 1;

        /*
         * create the httppost item with the webservice information and the
         * new id to put the story under
         */
        httpPost = new HttpPost("http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + nextId);
        story.setOnlineStoryId(nextId);
    } else {
        /*
         * create the httppost item with the webservice information and the
         * story's online id so that it upates that item
         */
        httpPost = new HttpPost(
                "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + story.getOnlineStoryId());
    }

    /* convert the story object to JSON format */
    StringEntity stringentity = null;
    try {
        stringentity = new StringEntity(gson.toJson(story));
    } catch (UnsupportedEncodingException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    }

    /*
     * set the httppost so that it knows it is accepting a JSON formatted
     * object to add
     */
    httpPost.setHeader("Accept", "application/json");
    /* set the object to add into the httppost */
    httpPost.setEntity(stringentity);

    HttpResponse response = getHttpResponse(httpPost);
    /* Retrieve and print to the log cat the status result of the post */
    String status = response.getStatusLine().toString();
    Log.d(TAG, status);

    HttpEntity entity = response.getEntity();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        String output;

        Log.d(TAG, "Output from Server -> ");
        while ((output = br.readLine()) != null) {
            Log.d(TAG, output);
        }
    } catch (IllegalStateException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    } catch (IOException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    }

    /*
     * return back to the calling class the online story id for the story
     * object added or updated
     */
    return story.getOnlineStoryId();
}

From source file:com.LMO.capstone.KnoWITHerbalMain.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/*from  w w  w. j a  v  a 2  s.  c o  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
    title = "";
    navTitles = getResources().getStringArray(R.array.navigationMenus);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    drawerList = (ListView) findViewById(R.id.nav_list);
    drawer = (LinearLayout) findViewById(R.id.drawer_view);
    util = new Utilities(this);

    drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    drawerList.setAdapter(new MenuListAdapter(this, navTitles));
    drawerList.setOnItemClickListener(new DrawerItemClickListener());
    drawerList.setSelector(R.drawable.listitem_selector);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6AD600"))); //light green = 6ad600, dark = 00cc00
    getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_launcher_2));

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(title);
            supportInvalidateOptionsMenu();
        }

        public void onDrawerOpened(View view) {
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle("Menu");
            supportInvalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    //FIRST RUN OF THE APPLICATION============================================
    if (savedInstanceState == null) {
        FragmentTransaction fTransac = getSupportFragmentManager().beginTransaction();
        fTransac.replace(R.id.frame_content, new Welcome()).commit();

        try {
            resolver();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    //END OF FIRST RUN OF THE APPLICATION============================================

    /*try {
       ViewConfiguration config = ViewConfiguration.get(this);
       Field menuKeyField = ViewConfiguration.class
       .getDeclaredField("sHasPermanentMenuKey");
       if (menuKeyField != null) {
    menuKeyField.setAccessible(true);
    menuKeyField.setBoolean(config, false);
    }
    }
    catch (Exception e) {
       e.printStackTrace();
    }*/
}