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:org.videolan.vlc.gui.VLCMainActivity.java

@SuppressLint("NewApi")
@Override/*from  w  w  w.  j av a2 s  . co  m*/
protected void onCreate(Bundle savedInstanceState) {

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

    if (!LibVlcUtil.hasCompatibleCPU(this)) {
        Log.e(TAG, LibVlcUtil.getErrorMsg());
        Intent i = new Intent(this, CompatErrorActivity.class);
        startActivity(i);
        finish();
        super.onCreate(savedInstanceState);
        return;
    }

    /* Get the current version from package */
    PackageInfo pinfo = null;
    try {
        pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (NameNotFoundException e) {
        Log.e(TAG, "package info not found.");
    }
    if (pinfo != null)
        mVersionNumber = pinfo.versionCode;

    /* Get settings */
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);

    /* Check if it's the first run */
    mFirstRun = mSettings.getInt(PREF_FIRST_RUN, -1) != mVersionNumber;
    if (mFirstRun) {
        Editor editor = mSettings.edit();
        editor.putInt(PREF_FIRST_RUN, mVersionNumber);
        editor.commit();
    }

    try {
        // Start LibVLC
        VLCInstance.getLibVlcInstance();
    } catch (LibVlcException e) {
        //e.printStackTrace();
        Intent i = new Intent(this, CompatErrorActivity.class);
        i.putExtra("runtimeError", true);
        i.putExtra("message", "LibVLC failed to initialize (LibVlcException)");
        startActivity(i);
        finish();
        super.onCreate(savedInstanceState);
        return;
    }

    super.onCreate(savedInstanceState);

    /*** Start initializing the UI ***/

    /* Enable the indeterminate progress feature */
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enableBlackTheme = pref.getBoolean("enable_black_theme", false);
    if (enableBlackTheme)
        setTheme(R.style.Theme_VLC_Black);

    View v_main = LayoutInflater.from(this).inflate(R.layout.main, null);
    setContentView(v_main);

    mSlidingPane = (SlidingPaneLayout) v_main.findViewById(R.id.pane);
    mSlidingPane.setPanelSlideListener(mPanelSlideListener);

    mListView = (ListView) v_main.findViewById(R.id.sidelist);
    mListView.setFooterDividersEnabled(true);
    mSidebarAdapter = new SidebarAdapter(this);
    mListView.setAdapter(mSidebarAdapter);

    /* Initialize UI variables */
    mInfoLayout = v_main.findViewById(R.id.info_layout);
    mInfoProgress = (ProgressBar) v_main.findViewById(R.id.info_progress);
    mInfoText = (TextView) v_main.findViewById(R.id.info_text);
    mAudioPlayerFilling = v_main.findViewById(R.id.audio_player_filling);
    mRootContainer = (DrawerLayout) v_main.findViewById(R.id.root_container);

    /* Set up the action bar */
    // commit for android 4.1...tempory
    //        prepareActionBar(); 

    /* Set up the sidebar click listener
     * no need to invalidate menu for now */
    mDrawerToggle = new ActionBarDrawerToggle(this, mRootContainer, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {
    };

    // Set the drawer toggle as the DrawerListener
    mRootContainer.setDrawerListener(mDrawerToggle);
    // set a custom shadow that overlays the main content when the drawer opens
    mRootContainer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    //        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //        getSupportActionBar().setHomeButtonEnabled(true);

    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SidebarAdapter.SidebarEntry entry = (SidebarEntry) mListView.getItemAtPosition(position);
            Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);

            if (current == null || (entry != null && current.getTag().equals(entry.id))) {
                /* Already selected */
                mRootContainer.closeDrawer(mListView);
                return;
            }

            // This should not happen
            if (entry == null || entry.id == null)
                return;

            /*
             * Clear any backstack before switching tabs. This avoids
             * activating an old backstack, when a user hits the back button
             * to quit
             */
            getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

            /* Slide down the audio player */
            slideDownAudioPlayer();

            /* Switch the fragment */
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.fragment_placeholder, getFragment(entry.id), entry.id);
            ft.commit();
            mCurrentFragment = entry.id;

            /*
             * Set user visibility hints to work around weird Android
             * behaviour of duplicate context menu events.
             */
            current.setUserVisibleHint(false);
            getFragment(mCurrentFragment).setUserVisibleHint(true);
            // HACK ALERT: Set underlying audio browser to be invisible too.
            if (current.getTag().equals("tracks"))
                getFragment("audio").setUserVisibleHint(false);

            mRootContainer.closeDrawer(mListView);
        }
    });

    /* Set up the audio player */
    mAudioPlayer = new AudioPlayer();
    mAudioController = AudioServiceController.getInstance();

    getSupportFragmentManager().beginTransaction().replace(R.id.audio_player, mAudioPlayer).commit();

    if (mFirstRun) {
        /*
         * The sliding menu is automatically opened when the user closes
         * the info dialog. If (for any reason) the dialog is not shown,
         * open the menu after a short delay.
         */
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRootContainer.openDrawer(mListView);
            }
        }, 500);
    }

    /* Prepare the progressBar */
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_SHOW_PROGRESSBAR);
    filter.addAction(ACTION_HIDE_PROGRESSBAR);
    //        filter.addAction(ACTION_SHOW_TEXTINFO);
    filter.addAction(ACTION_SHOW_PLAYER);
    registerReceiver(messageReceiver, filter);

    /* Reload the latest preferences */
    reloadPreferences();
}

From source file:com.ti.sensortag.gui.services.ServicesActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakelockk = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
    setContentView(R.layout.services_browser);

    //for checking signal strength..
    MyListener = new MyPhoneStateListener();
    Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    //ends..//from  w w w.  j  av  a 2s.  c o  m

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    test_1 = getIntent().getStringExtra("TEST");
    Toast.makeText(getBaseContext(), "ARV in services SA :" + test_1, Toast.LENGTH_SHORT).show();

    /* sendbutton = (Button) findViewById(R.id.button1);
    sendbutton.setOnClickListener(new OnClickListener() {
              
      @Override
      public void onClick(View v) {
         // TODO Auto-generated method stub
         String sensorid = test_1;
         String sensortype = "temperature";
         BufferedReader br = null;
                  
         try {
            
    String sCurrentLine;
            
    File ext = Environment.getExternalStorageDirectory();
    File myFile = new File(ext, "mysdfile_25.txt");
            
    br = new BufferedReader(new FileReader(myFile));
            
    while ((sCurrentLine = br.readLine()) != null) {
       String[] numberSplit = sCurrentLine.split(":") ; 
       String time = numberSplit[ (numberSplit.length-2) ] ;
       String val = numberSplit[ (numberSplit.length-1) ] ;
       //System.out.println(sCurrentLine);
       HttpResponse httpresponse;
       //int responsecode;
       StatusLine responsecode;
       String strresp;
               
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost("https://rnicu-cloud.appspot.com/sensor/update");
               
       try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
           nameValuePairs.add(new BasicNameValuePair("sensorid", sensorid));
           nameValuePairs.add(new BasicNameValuePair("sensortype", sensortype));
           nameValuePairs.add(new BasicNameValuePair("time", time));
           nameValuePairs.add(new BasicNameValuePair("val", val));
         //  try {
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //      try {
             httpresponse = httpclient.execute(httppost);
             //responsecode = httpresponse.getStatusLine().getStatusCode();
             responsecode = httpresponse.getStatusLine();
             strresp = responsecode.toString();
             Log.d("ARV Response msg from post", httpresponse.toString());
             Log.d("ARV status of post", strresp);
             HttpEntity httpentity = httpresponse.getEntity();
             Log.d("ARV entity string", EntityUtils.toString(httpentity));
          //   Log.d("ARV oly entity", httpentity.toString());
          //   Log.d("ARV Entity response", httpentity.getContent().toString());
             //httpclient.execute(httppost);
             Toast.makeText(getApplicationContext(), "Posted data and returned value:"+ strresp, Toast.LENGTH_LONG).show();
    //      } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (IOException e) {
             // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }
    //   } 
       }catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
            
         } catch (IOException e) {
    e.printStackTrace();
         } finally {
    try {
       if (br != null)br.close();
    } catch (IOException ex) {
       ex.printStackTrace();
    }
         }
                 
                 
      //   Toast.makeText(getApplicationContext(), "Entered on click", Toast.LENGTH_SHORT).show();
                 
                 
         /*catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
         }   
      }
    });*/

    getActionBar().setDisplayHomeAsUpEnabled(true);
}

From source file:com.ohnemax.android.glass.doseview.CSDataSort.java

@Override
public void onCreate() {
    // Just for testing, allow network access in the main thread
    // NEVER use this is productive code
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate();
    mRanGen = new Random();

    new CheckConnectivityTask().execute();
    initializeLocationManager();/*from  w  w  w.  ja va  2s .com*/
}

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

public boolean RemovePointss(int numpoints) {

    int currentpoints = 0;
    Connection conn = null;/*  w  w w.  ja  va2 s  . c o  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='" + re + "'";
    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));
            currentpoints = rs.getInt(7);
        }
    } catch (SQLException e) {
        return false;
    }
    String pro = "EXEC dbo.addpoints ?,?";
    PreparedStatement ps = null;
    try {
        ps = conn.prepareStatement(pro);
        ps.setEscapeProcessing(true);
        ps.setInt(1, Integer.parseInt(re));
        ps.setInt(2, currentpoints - numpoints);
        ps.execute();
    } catch (SQLException e) {
        return false;
    }

    return true;
}

From source file:org.chromium.latency.walt.MainActivity.java

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

    // App bar/*w  ww  .  j a va2 s .com*/
    toolbar = (Toolbar) findViewById(R.id.toolbar_main);
    setSupportActionBar(toolbar);
    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            int stackTopIndex = getSupportFragmentManager().getBackStackEntryCount() - 1;
            if (stackTopIndex >= 0) {
                toolbar.setTitle(getSupportFragmentManager().getBackStackEntryAt(stackTopIndex).getName());
            } else {
                toolbar.setTitle(R.string.app_name);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                // Disable fullscreen mode
                getSupportActionBar().show();
                getWindow().getDecorView().setSystemUiVisibility(0);
            }
        }
    });

    waltDevice = WaltDevice.getInstance(this);

    // Create front page fragment
    FrontPageFragment frontPageFragment = new FrontPageFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_container, frontPageFragment);
    transaction.commit();

    logger = SimpleLogger.getInstance(this);
    broadcastManager = LocalBroadcastManager.getInstance(this);

    // Add basic version and device info to the log
    logger.log(String.format("WALT v%s  (versionCode=%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
    logger.log("WALT protocol version " + WaltDevice.PROTOCOL_VERSION);
    logger.log("DEVICE INFO:");
    logger.log("  " + Build.FINGERPRINT);
    logger.log("  Build.SDK_INT=" + Build.VERSION.SDK_INT);
    logger.log("  os.version=" + System.getProperty("os.version"));

    // Set volume buttons to control media volume
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    requestSystraceWritePermission();
    // Allow network operations on the main thread
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

From source file:sjizl.com.FileUploadTest.java

@SuppressLint("NewApi")
@Override/*w  w  w .  j  a  v a2 s.  co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.fileuploadtest2);
    //ac_image_grid
    TextView textView2_under_title;
    final ImageLoader imageLoader = ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
    progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
    progressBar_hole.setVisibility(View.INVISIBLE);
    right_lin = (LinearLayout) findViewById(R.id.right_lin);
    rand = CommonUtilities.randInt(111, 999);
    middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
    //right_lin.setBackgroundColor(Color.BLUE);
    right_lin = (LinearLayout) findViewById(R.id.right_lin);
    left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);

    left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
    left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
    middle_lin = (LinearLayout) findViewById(R.id.middle_lin);

    upload_photo_text = (LinearLayout) findViewById(R.id.upload_photo_text);

    textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
    ((LinearLayout) textView2_under_title.getParent()).removeView(textView2_under_title);
    textView2_under_title.setVisibility(View.GONE);
    ImageView imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    Button upload_photo0 = (Button) findViewById(R.id.upload_photo0);
    Button upload_photo1 = (Button) findViewById(R.id.upload_photo1);
    Button upload_photo2 = (Button) findViewById(R.id.upload_photo2);

    upload_photo0.setVisibility(View.GONE);
    upload_photo1.setVisibility(View.GONE);
    upload_photo2.setVisibility(View.GONE);

    upload_photo0.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this, "UploadActivity! ", null,
                    R.drawable.iconbd);

            Intent dashboard = new Intent(getApplicationContext(), UploadActivity.class);

            startActivity(dashboard);
        }
    });
    upload_photo1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(getApplicationContext(), "FileChooserExampleActivity!", Toast.LENGTH_LONG).show();
            Intent dashboard = new Intent(getApplicationContext(), FileChooserExampleActivity.class);

            startActivity(dashboard);
        }
    });

    upload_photo2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "FileChooserExampleActivity!", Toast.LENGTH_LONG).show();
            Intent dashboard = new Intent(getApplicationContext(), FileChooserExampleActivity.class);

            startActivity(dashboard);
        }
    });

    final ImageView left_button;

    left_button = (ImageView) findViewById(R.id.imageView1_back);
    Button button1 = (Button) findViewById(R.id.upload_photo1);

    SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
    naam = sp.getString("naam", null);
    username = sp.getString("username", null);
    password = sp.getString("password", null);
    foto = sp.getString("foto", null);
    foto_num = sp.getString("foto_num", null);
    imageLoader.displayImage("http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, imageView2_dashboard,
            options);

    Brows();

    listView.setLongClickable(true);
    registerForContextMenu(listView);

    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //startImagePagerActivity(position);

            if (position == 0) {
                openGallery(SELECT_FILE1);
            } else {

                listView.showContextMenuForChild(view);
                //  registerForContextMenu(view); 
                //  openContextMenu(view);
                //  unregisterForContextMenu(view);
            }

        }
    });

    left_lin1.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE
                    || event.getAction() == MotionEvent.ACTION_POINTER_DOWN) {
                left_lin1.setBackgroundColor(Color.DKGRAY);
                v.setBackgroundColor(Color.DKGRAY);
                onBackPressed();
            } else if (event.getAction() == MotionEvent.ACTION_UP
                    || event.getAction() == MotionEvent.ACTION_CANCEL) {
                left_lin1.setBackgroundColor(Color.BLACK);
                v.setBackgroundColor(Color.BLACK);
            }
            return false;
        }
    });
    CommonUtilities u = new CommonUtilities();
    u.setHeaderConrols(getApplicationContext(), this,

            right_lin,

            left_lin3, left_lin4, left_lin1, left_button);
    ;

    middle_lin.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE
                    || event.getAction() == MotionEvent.ACTION_POINTER_DOWN) {
                middle_lin.setBackgroundColor(Color.DKGRAY);
                v.setBackgroundColor(Color.DKGRAY);
            } else if (event.getAction() == MotionEvent.ACTION_UP
                    || event.getAction() == MotionEvent.ACTION_CANCEL) {
                middle_lin.setBackgroundColor(Color.BLACK);
                v.setBackgroundColor(Color.BLACK);
            }
            return false;
        }
    });

}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 *Get Uri for HTTP Content/*from ww w  . j a  va2 s .  co m*/
 * @param path HTTP adress
 * @return Uri of the downloaded file
 */
private Uri getUriForHTTP(String path) {
    try {
        URL url = new URL(path);
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        String resName = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = path.substring(path.lastIndexOf('.'));
        File dir = activity.getExternalCacheDir();
        if (dir == null) {
            Log.e("Asset", "Missing external cache dir");
            return Uri.EMPTY;
        }
        String storage = dir.toString() + STORAGE_FOLDER;
        File file = new File(storage, resName + extension);
        new File(storage).mkdir();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

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

        StrictMode.setThreadPolicy(policy);

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();
        FileOutputStream outStream = new FileOutputStream(file);
        copyFile(input, outStream);
        outStream.flush();
        outStream.close();

        return Uri.fromFile(file);
    } catch (MalformedURLException e) {
        Log.e("Asset", "Incorrect URL");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Log.e("Asset", "Failed to create new File from HTTP Content");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Asset", "No Input can be created from http Stream");
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.example.admin.parkingappfinal.MainActivity.java

public void update() {
    ImageView a1on = (ImageView) findViewById(R.id.imageView);
    ImageView a1off = (ImageView) findViewById(R.id.A1off);
    ImageView a2on = (ImageView) findViewById(R.id.A2on);
    ImageView a2off = (ImageView) findViewById(R.id.A2off);
    ImageView b1on = (ImageView) findViewById(R.id.B1on);
    ImageView b1off = (ImageView) findViewById(R.id.B1off);
    try {//from  w ww .j a v  a  2 s  . c o  m
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, user, pass);

        String result = "Database connection success\n";
        System.out.println("We made it here");
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from Lot1");
        ResultSetMetaData rsmd = rs.getMetaData();
        //System.out.println(rs.getString(1));
        //System.out.println(rs.getString(2));
        //System.out.println(rs.getString(3));
        while (rs.next()) {
            //System.out.println(rs.getString(1));
            //System.out.println(rs.getString(2));
            //System.out.println(rs.getString(3));
            //result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
            result += rsmd.getColumnName(2) + ":" + rs.getString(2);
            result += rsmd.getColumnName(3) + ":" + rs.getString(3);
        }
        //System.out.println(result);
        for (int i = 0; i < 3; i++) {
            spaces[i] = result.substring(result.indexOf(":") + 1, result.indexOf(":") + 3);
            String newResult = result.substring(result.indexOf(":") + 3);
            System.out.println(newResult);
            filled[i] = Integer
                    .parseInt(newResult.substring(newResult.indexOf(":") + 1, newResult.indexOf(":") + 2));
            result = newResult.substring(newResult.indexOf(":") + 2);
        }
        System.out.println(Arrays.toString(spaces));
        System.out.println(Arrays.toString(filled));
        //tv.setText(result);
        if (filled[0] == 1) {
            a1on.bringToFront();
        }
        if (filled[0] == 0) {
            a1off.bringToFront();
        }
        if (filled[1] == 1) {
            a2on.bringToFront();
        }
        if (filled[1] == 0) {
            a2off.bringToFront();
        }
        if (filled[2] == 1) {
            b1on.bringToFront();
        }
        if (filled[2] == 0) {
            b1off.bringToFront();
        }
    } catch (Exception e) {
        e.printStackTrace();
        //tv.setText(e.toString());
    }
}

From source file:com.myapps.playnation.main.MainActivity.java

@SuppressLint("NewApi")
private void miniSetup() {
    if (android.os.Build.VERSION.SDK_INT > 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }//from w  ww.j av a 2 s  .  c  o  m
    // requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    getSupportActionBar().setTitle("Playnation Mobile");
    getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.background_gradient));
    con = DataConnector.getInst();
    Log.i("MainActiv", "intent.getInt() = " + getIntent().getExtras().getInt(Keys.AppState));
    isTablet = Configurations.getConfigs().isTablet();
    if (!isTablet)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setSupportProgressBarIndeterminateVisibility(true);
}

From source file:org.openmrs.mobile.activities.DashboardActivity.java

void getPatientData() throws Exception {
    /*// w w w.  jav  a 2  s  .c om
    * SET VALUE FOR CONNECT TO OPENMRS
    */
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ApiAuthRest.setURLBase("http://bupaopenmrs.cloudapp.net/openmrs/ws/rest/v1/person/");
    ApiAuthRest.setUsername("diana");
    ApiAuthRest.setPassword("Admin123");

    /*
     * Example how parse json return session
     */

    String request = Container.user_uuid;
    Object obj = ApiAuthRest.getRequestGet(request);
    JSONObject jsonObject = new JSONObject((String) obj);
    Log.d("Profile page", (String) obj);

    Container.patient_name = jsonObject.getString("display");
    Container.patient_gender = jsonObject.getString("gender");

    if (Container.patient_gender.matches("M")) {
        Container.patient_gender = "Male";
    } else {
        Container.patient_gender = "Female";
    }

    Container.patient_age = jsonObject.getString("age");
    Container.patient_birthdate = jsonObject.getString("birthdate");
    Container.patient_birthdate = Container.patient_birthdate.substring(0, 10);
}