Exemplo n.º 1
1
 public void onRadioButtonClicked(View v) {
   if (v.getId() == R.id.group_closed_radio) {
     groupLogo.setImageResource(R.drawable.group_closed);
     groupLogo.setBackgroundColor(R.color.color_primary);
     groupTypeDescr.setText(R.string.group_closed_description);
     Log.e(
         TAG,
         "Cliccato: "
             + v.getId()
             + "! Setto: "
             + R.drawable.group_closed
             + ", "
             + R.color.color_primary
             + ", "
             + R.string.group_closed_description);
   } else if (v.getId() == R.id.group_open_radio) {
     groupLogo.setImageResource(R.drawable.group_open);
     groupLogo.setBackgroundColor(R.color.color_primary);
     groupTypeDescr.setText(R.string.group_open_description);
     Log.e(
         TAG,
         "Cliccato: "
             + v.getId()
             + "! Setto: "
             + R.drawable.group_open
             + ", "
             + R.color.color_primary
             + ", "
             + R.string.group_open_description);
   }
 }
Exemplo n.º 2
1
 public static void load(Activity a, int R_layout_yourXML) {
   a.setContentView(R_layout_yourXML);
   Views.inject(a); // butterknife injection
   String className = a.getClass().getCanonicalName() + "$$ViewInjector";
   try {
     Log.i(LOG_TAG, "Checking if butterknife injections exist" + ", className=" + className);
     Class.forName(className);
   } catch (ClassNotFoundException e) {
     // injection did not work show instructions:
     Log.e(
         LOG_TAG,
         "! Butterknife could not find injection classes "
             + "(see http://jakewharton.github.io/"
             + "butterknife/ide-eclipse.html )");
     Log.e(
         LOG_TAG,
         "! Right click on project -> "
             + "Head to Java Compiler -> Annotation "
             + "Processing -> CHECK 'Enable project "
             + "specific settings'");
     Log.e(
         LOG_TAG,
         "! Select 'Factory Path' -> "
             + "Check \"Enable project specific settings\" "
             + "-> click \"Add JARs\" -> Navigate to the "
             + "project's libs/ folder and select "
             + "the Butter Knife jar -> Click Ok");
     throw new RuntimeException(
         "Butterknife could not " + "find injection class '" + className + "'");
   }
 }
  public static String printKeyHash(Activity context) {
    PackageInfo packageInfo;
    String key = null;
    try {
      // getting application package name, as defined in manifest
      String packageName = context.getApplicationContext().getPackageName();

      // Retriving package info
      packageInfo =
          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);

      Log.e("Package Name=", context.getApplicationContext().getPackageName());

      for (Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));

        // String key = new String(Base64.encodeBytes(md.digest()));
        Log.e("Key Hash=", key);
      }
    } catch (PackageManager.NameNotFoundException e1) {
      Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
      Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
      Log.e("Exception", e.toString());
    }

    return key;
  }
Exemplo n.º 4
0
  public static CharMappingSaveData[] readCharMappingFromResource(Context context) {
    InputStream is = context.getResources().openRawResource(R.raw.albhabet);
    CharMappingSaveData[] saveData = null;

    ObjectInputStream ois = null;
    try {
      ois = new ObjectInputStream(is);
      saveData = (CharMappingSaveData[]) ois.readObject();
    } catch (IOException ex) {
      Log.e(TAG, "Failed to read char mapping from resource.", ex);
    } catch (ClassNotFoundException ex) {
      Log.e(TAG, "Failed to read char mapping from resource.", ex);
    } finally {
      try {
        is.close();
      } catch (IOException ex) {
      }
      if (ois != null) {
        try {
          ois.close();
        } catch (IOException e) {
        }
      }
    }

    return saveData;
  }
Exemplo n.º 5
0
  /**
   * retrieve the auth token string securely
   *
   * @param context Context used to read storage
   * @return String of the stored access token, returns "" if no access token exists.
   */
  public static String getAccessToken(Context context) {
    String accessToken = "";
    String filename = getAccessTokenFilename(context.getApplicationContext());
    File authFile = context.getDir(filename, Context.MODE_PRIVATE);
    try {
      if (!authFile.exists()) {
        Log.e(
            AppBlade.LogTag, "Trying to create Authfile location : " + authFile.getAbsolutePath());
        authFile.mkdirs();
        authFile.createNewFile();
      }
      FileInputStream fis = context.openFileInput(filename);
      InputStreamReader inputStreamReader = new InputStreamReader(fis);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      accessToken = bufferedReader.readLine();
    } catch (Exception ex) {
      Log.w(AppBlade.LogTag, "Error creating Access Token ", ex);
    }
    if (!authFile.exists()) {
      Log.e(AppBlade.LogTag, "Did not create Authfile location : " + authFile);
    }

    Log.v(
        AppBlade.LogTag, String.format("getAccessToken File:%s, token:%s", filename, accessToken));
    return accessToken;
  }
Exemplo n.º 6
0
    @Override
    public Void doInBackground(String... params) {
      HttpsURLConnection connection = null;

      try {
        URL url = new URL(SEARCH_URL + params[0]);
        Log.d("****URL:", url.toString());
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "JustDoIt");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
        connection.setUseCaches(false);

        JSONObject obj = new JSONObject(ReadResponse.readResponse(connection));

        buildTweets(obj);

        Log.d("***GetTweets:", obj.toString());

      } catch (MalformedURLException e) {
        Log.e("***GetTweets", "Invalid endpoint URL specified.", e);

      } catch (IOException e) {
        Log.e("***GetTweets", "IOException: ", e);
      } catch (JSONException e) {
        e.printStackTrace();
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
        lock.release();
      }
      return null;
    }
  @Override
  protected String doInBackground(String... params) {
    try {
      String postCode = params[0];

      String link = "http://weaverprojects.com/instagram/loadsinglepost.php";
      String data =
          URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode("SOME_HIDDEN_CODE", "UTF-8");
      data += "&";
      data += URLEncoder.encode("code", "UTF-8") + "=" + URLEncoder.encode(postCode, "UTF-8");

      URL url = new URL(link);
      URLConnection conn = url.openConnection();

      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

      wr.write(data);
      wr.flush();

      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line);
        break;
      }
      return sb.toString();
    } catch (Exception e) {
      Log.e(TAG, "Error: on in app");
      Log.e(TAG, e.toString());
      return "Failed In App";
    }
  }
Exemplo n.º 8
0
 public String streamtostring(InputStream is) {
   // convert response to string
   try {
     int length;
     if (is.available() > 0) length = is.available();
     else length = 1;
     BufferedReader reader = new BufferedReader(new InputStreamReader(is), length);
     StringBuilder sb = new StringBuilder();
     String line = null;
     while ((line = reader.readLine()) != null) {
       sb.append(line);
     }
     String result = sb.toString();
     is.close();
     reader = null;
     sb = null;
     Log.e("Received data", "" + result);
     this.result = result;
     return result;
   } catch (Exception e) {
     Log.e("log_tag", "Error converting result " + e.toString());
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 9
0
  /**
   * Wipe the device.
   *
   * @param code - Operation code.
   * @param data - Data required by the operation(PIN).
   */
  public void wipeDevice(String code, String data) {
    String inputPin;
    String savedPin = Preference.getString(context, resources.getString(R.string.shared_pref_pin));

    try {
      JSONObject wipeKey = new JSONObject(data);
      inputPin = (String) wipeKey.get(resources.getString(R.string.shared_pref_pin));
      String status;
      if (inputPin.trim().equals(savedPin.trim())) {
        status = resources.getString(R.string.shared_pref_default_status);
      } else {
        status = resources.getString(R.string.shared_pref_false_status);
      }

      resultBuilder.build(code, status);

      if (inputPin.trim().equals(savedPin.trim())) {
        Toast.makeText(context, resources.getString(R.string.toast_message_wipe), Toast.LENGTH_LONG)
            .show();
        try {
          Thread.sleep(PRE_WIPE_WAIT_TIME);
        } catch (InterruptedException e) {
          Log.e(TAG, "Wipe pause interrupted :" + e.toString());
        }
        devicePolicyManager.wipeData(ACTIVATION_REQUEST);
      } else {
        Toast.makeText(
                context, resources.getString(R.string.toast_message_wipe_failed), Toast.LENGTH_LONG)
            .show();
      }
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }
  }
Exemplo n.º 10
0
 /** Lazy initializes the {@link GCMBroadcastReceiver} instance. */
 static synchronized void setRetryBroadcastReceiver(Context context) {
   if (sRetryReceiver == null) {
     if (sRetryReceiverClassName == null) {
       // should never happen
       Log.e(TAG, "internal error: retry receiver class not set yet");
       sRetryReceiver = new GCMBroadcastReceiver();
     } else {
       Class<?> clazz;
       try {
         clazz = Class.forName(sRetryReceiverClassName);
         sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
       } catch (Exception e) {
         Log.e(
             TAG,
             "Could not create instance of "
                 + sRetryReceiverClassName
                 + ". Using "
                 + GCMBroadcastReceiver.class.getName()
                 + " directly.");
         sRetryReceiver = new GCMBroadcastReceiver();
       }
     }
     String category = context.getPackageName();
     IntentFilter filter = new IntentFilter(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
     filter.addCategory(category);
     // must use a permission that is defined on manifest for sure
     String permission = category + ".permission.C2D_MESSAGE";
     Log.v(TAG, "Registering retry receiver");
     sRetryReceiverContext = context;
     sRetryReceiverContext.registerReceiver(sRetryReceiver, filter, permission, null);
   }
 }
  public String execSu(String cmd) {
    Log.d(TAG, "^ Executing as SU '" + cmd + "'");
    try {
      Process process = Runtime.getRuntime().exec("su");
      DataInputStream is = new DataInputStream(process.getInputStream());
      DataOutputStream os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(cmd + "\n");
      os.writeBytes("exit\n");
      os.flush();
      os.close();

      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      try {
        String fullOutput = "";
        String line;
        while ((line = reader.readLine()) != null) {
          fullOutput = fullOutput + line + "\n";
        }
        return fullOutput;
      } catch (IOException e) { // It seems IOException is thrown when it reaches EOF.
        e.printStackTrace();
        Log.e(TAG, "^ execSU, IOException 1");
      }
      process.waitFor();

    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, IOException 2");
    } catch (InterruptedException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, InterruptedException");
    }
    return "";
  }
Exemplo n.º 12
0
 @Override
 public void onRequestPermissionsResult(
     int requestCode, String permissions[], int[] grantResults) {
   Log.d(TAG, "onRequestPermissionsResult: ");
   switch (requestCode) {
     case PERMISSIONS_REQUEST_ALL_PERMISSIONS:
       boolean hasAllPermissions = true;
       for (int i = 0; i < grantResults.length; ++i) {
         if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
           hasAllPermissions = false;
           Log.e(TAG, "Unable to get permission " + permissions[i]);
         }
       }
       if (hasAllPermissions) {
         finish();
       } else {
         Toast.makeText(this, "Unable to get all required permissions", Toast.LENGTH_LONG).show();
         finish();
         return;
       }
       break;
     default:
       Log.e(TAG, "Unexpected request code");
   }
 }
Exemplo n.º 13
0
  /**
   * 批量上传图片
   *
   * @param path 服务器地址
   * @param name 用户名
   * @param filePath sd卡图片路径
   * @param onSuccessListner
   * @return
   * @throws Exception
   */
  public static String sendDataByHttpClientPost(
      String path, List<File> files, List<Part> mparameters, OnSuccessListner listner)
      throws Exception {

    for (int i = 0; i < files.size(); i++) {
      mparameters.add(new FilePart("file", files.get(i)));
    }
    Part[] parts = mparameters.toArray(new Part[0]);

    PostMethod filePost = new PostMethod(path);
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    if (status == 200) {
      Log.e("DataService", "" + filePost.getResponseCharSet());
      String result = new String(filePost.getResponseBodyAsString());
      Log.e("DataService", "--" + result);
      // JSONArray array = (JSONArray) JSON.parse(result);
      Log.e("JSONArray", "--" + result);
      listner.onSuccess(result);
      return result;
    } else {
      listner.onFailed();
      return null;
    }
  }
Exemplo n.º 14
0
  @Override
  public boolean onInterceptTouchEvent(MotionEvent ev) {
    Log.e("mcoy", "McoyScrollView--onInterceptTouchEvent");
    switch (ev.getAction()) {
      case MotionEvent.ACTION_DOWN:
        xDistance = yDistance = 0f;
        xLast = ev.getX();
        yLast = ev.getY();
        break;
      case MotionEvent.ACTION_MOVE:
        final float curX = ev.getX();
        final float curY = ev.getY();

        xDistance += Math.abs(curX - xLast);
        yDistance += Math.abs(curY - yLast);
        xLast = curX;
        yLast = curY;

        if (xDistance > yDistance) {
          return false;
        }
    }
    boolean onIntercept = super.onInterceptTouchEvent(ev);
    Log.e("mcoy", "McoyScrollView--onInterceptTouchEvent return " + onIntercept);

    return onIntercept;
  }
Exemplo n.º 15
0
  @Override
  public void NotifyDataChanged(int notifyType) {
    switch (notifyType) {
        // 网络加载的备料单列表发生变化
      case NOTICE_PREPARE_ADAPTER:
        if (prepareAdapter != null) {
          prepareAdapter.notifyDataSetChanged();
          Log.i("Inmake:NotifyItem", prepareDataList.toString());
          showNullItemImg(prepareDataList, nullItemLayoutPrepare);
        }

        loadingView.dismiss();
        break;
        // 搜索的备料单列表发生变化
      case NOTICE_SEARCH_ADAPTER:
        Log.e("Inmake:NotifyItem", "searchItemList" + searchItemList.toString());
        if (searchAdapter != null) {
          searchAdapter.notifyDataSetChanged();
          Log.e("Inmake:NotifyItem", searchItemList.toString());
          showNullItemImg(searchItemList, nullItemLayoutSearch);
        }
        loadingView.dismiss();
        break;
    }
  }
Exemplo n.º 16
0
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    try {
      info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
      Log.e(TAG, "bad menuInfo", e);
      return false;
    }

    switch (item.getItemId()) {
      case MENU_ITEM_DELNOTE:
        {
          Log.e(TAG, "MENU_ITEM_DELFAVORITE id = " + info.id);

          dao.delete(info.id);

          loadNoteList();
          return true;
        }
      case MENU_ITEM_BIBLEVIEW:
        {
          Log.e(TAG, "MENU_ITEM_SONGVIEW uri = " + item.getIntent().getData().toString());
          startActivity(item.getIntent());
          return true;
        }
    }
    return false;
  }
 @Override
 public void handleMessage(Message msg) {
   switch (msg.what) {
     case MSG_REFLESH_DONE:
       if (null != mListView) {
         if (null != mAdapter) {
           mAdapter.clear();
           for (int i = 0; i < 30; i++) {
             mDatas.add("Item " + mDatas.size());
           }
           mAdapter.notifyDataSetChanged();
         }
         mListView.refreshCompleted();
         mListView.loadMoreCompleted(mDatas.size() < 50);
         Log.e(TAG, "Refresh finished +=====================^_^");
       }
       break;
     case MSG_LOAD_DONE:
       if (null != mListView) {
         if (null != mAdapter) {
           for (int i = 0; i < 30; i++) {
             mDatas.add("Item " + mDatas.size());
           }
           mAdapter.notifyDataSetChanged();
         }
         mListView.refreshCompleted();
         mListView.loadMoreCompleted(mDatas.size() < 50);
         Log.e(TAG, "Load more finished +=====================^_^");
       }
       break;
     default:
       break;
   }
   super.handleMessage(msg);
 }
Exemplo n.º 18
0
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    Log.e("appstorequery", "uri is " + uri.toString());
    Log.e("appstorequery", "seletcion is " + selection);
    Log.e("appstorequery", "selectionArgs is " + selectionArgs[0]);
    Log.e("appstorequery", "selectionArgs is " + selectionArgs[1]);

    selection = "url=? AND service_name=?";
    selectionArgs = new String[] {"http://www.baidu.com/1", "service1"};

    switch (uriMatcher.match(uri)) {
      case ITEMS:
        // Log.d("appstorequery", "uri is ITEMS ");
        return database.query(
            TABLE_URL_PERMISSIONS, projection, selection, selectionArgs, null, null, sortOrder);
      case ITEM:
        // Log.d("appstorequery", "uri is ITEM ");
        return database.query(
            TABLE_URL_PERMISSIONS,
            projection,
            _ID + "=" + uri.getPathSegments().get(1),
            selectionArgs,
            null,
            null,
            null);
      default:
        throw new IllegalArgumentException("unknown uri: " + uri);
    }
  }
Exemplo n.º 19
0
  /**
   * Stops all the device activities <br>
   * close session <br>
   * stop find adv name <br>
   * stop scheduled service <br>
   * Set is reachable to false
   */
  void stopDeviceActivities() {
    isReachable.set(false);

    try {
      connMgr.cancelFindAdvertisedName(sender);
    } catch (ControlPanelException cpe) {
      Log.e(TAG, "Failed to call cancelFindAdvertisedName(), Error: '" + cpe.getMessage() + "'");
    }

    connMgr.unregisterEventListener(ConnManagerEventType.FOUND_DEVICE, this);
    connMgr.unregisterEventListener(ConnManagerEventType.LOST_DEVICE, this);

    Status status = endSession();
    if (status != Status.OK) {
      Log.e(TAG, "Failed to end the session, Status: '" + status + "'");
    }

    stopDeviceFoundVerificationService();

    for (Unit unit : unitMap.values()) {
      unit.release();
    }

    unitMap.clear();
  } // stopDeviceActivities
Exemplo n.º 20
0
  public static String handleRetrofitErrorQuietly(final RetrofitError error) {
    error.printStackTrace();

    InputStream inputStream = null;
    try {
      if (error.isNetworkError()) {
        Log.e("XDA-ONE", "Network error happened.");
      } else {
        final TypedInput body = error.getResponse().getBody();
        if (body == null) {
          Log.e("XDA-ONE", "Unable to retrieve body");
          return null;
        }
        inputStream = body.in();

        final String result = IOUtils.toString(inputStream);
        Log.e("XDA-ONE", result);
        return result;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    return null;
  }
Exemplo n.º 21
0
  public void retrieveVcard() {

    ConnectionConfiguration conf =
        new ConnectionConfiguration(
            ConnectionManager.HOST, ConnectionManager.PORT, ConnectionManager.SERVICE);
    connection = new XMPPConnection(conf);
    ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider());

    try {
      connection.connect();

      Log.i("success", "successful connection to server");
    } catch (XMPPException e) {
      Log.e("unable to connect to the server", e.toString());
    }

    try {

      connection.login("admin", "xenomorph");
      gettingCard(connection);

    } catch (XMPPException ex) {
      Log.e("error logging in as user ", ex.toString());
    }
  }
Exemplo n.º 22
0
    @Override
    protected void onPostExecute(String sResponse) {
      try {
        if (dialog.isShowing()) {
          dialog.dismiss();

          firstexecution = 1989;
          ArrayAdapter<String> dataAdapter =
              new ArrayAdapter<String>(
                  TechnicienActivity.this, android.R.layout.simple_spinner_item, listclt);
          dataAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);

          // facturespinner.setAdapter(dataAdapter);
          addItemsOnSpinner(services, 3);

          // ArrayAdapter<String> dataAdapter = new
          // ArrayAdapter<String>(TechnicienActivity.this,android.R.layout.simple_dropdown_item_1line, listclt);
          clients.setAdapter(dataAdapter);
          clients.setThreshold(1);
          clients.setTextColor(Color.RED);

          for (BordreauIntervention b : myoffine.LoadInterventions("")) {
            Log.e(">> interv ", b.toString());
          }
          // wakelock.release();
        }

      } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage() + " << ", Toast.LENGTH_LONG).show();
        Log.e(e.getClass().getName(), e.getMessage() + " << ", e);
      }
    }
Exemplo n.º 23
0
  /**
   * Blacklisting apps.
   *
   * @param code - Operation code.
   * @param data - Data required(Application data).
   */
  public void blacklistApps(String code, String data) {
    ArrayList<DeviceAppInfo> apps = appList.getInstalledApps();
    JSONArray appList = new JSONArray();
    String identity = null;
    try {
      JSONObject resultApp = new JSONObject(data);
      if (!resultApp.isNull(resources.getString(R.string.intent_extra_data))) {
        resultApp = (JSONObject) resultApp.get(resources.getString(R.string.intent_extra_data));
      }

      identity = (String) resultApp.get(resources.getString(R.string.intent_extra_identity));
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }

    for (DeviceAppInfo app : apps) {
      JSONObject result = new JSONObject();
      try {
        result.put(resources.getString(R.string.intent_extra_name), app.getAppname());
        result.put(resources.getString(R.string.intent_extra_package), app.getPackagename());
        if (identity.trim().equals(app.getPackagename())) {
          result.put(resources.getString(R.string.intent_extra_not_violated), false);
          result.put(resources.getString(R.string.intent_extra_package), app.getPackagename());
        } else {
          result.put(resources.getString(R.string.intent_extra_not_violated), true);
        }

      } catch (JSONException e) {
        Log.e(TAG, "Invalid JSON format." + e);
      }
      appList.put(result);
    }

    resultBuilder.build(code, appList);
  }
Exemplo n.º 24
0
 private String readFromZipFile(String filename) {
   ZipFile zip = null;
   String str = null;
   try {
     InputStream fileStream = null;
     File applicationPackage = new File(mActivity.getApplication().getPackageResourcePath());
     zip = new ZipFile(applicationPackage);
     if (zip == null) return null;
     ZipEntry fileEntry = zip.getEntry(filename);
     if (fileEntry == null) return null;
     fileStream = zip.getInputStream(fileEntry);
     str = readStringFromStream(fileStream);
   } catch (IOException ioe) {
     Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
   } finally {
     try {
       if (zip != null) zip.close();
     } catch (IOException ioe) {
       // catch this here because we can continue even if the
       // close failed
       Log.e(LOGTAG, "error closing zip filestream", ioe);
     }
   }
   return str;
 }
	private void saveMyBitmap() {
		try {
		Bitmap bitmap = mGesture.toBitmap(240, 75, 12, Color.RED);
		// mImageView.setImageBitmap(bitmap);
		if(path == null || path.equals("") || path.equals("null")){
		path = Environment.getExternalStorageDirectory().toString();
		}
		Log.e("?????", path);
		
		  File destDir = new File(path);
		  if (!destDir.exists()) {
		   destDir.mkdirs();
		  }
		
		String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
				+ ".png";// 照片命名
		
		this.pathAndName = path + "/"+name;
		File f = new File(pathAndName);
		
		
		FileOutputStream fos = null;
		
			fos = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
			Toast.makeText(getApplicationContext(), "保存成功", 5000).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e("Exception", e.getMessage());
			e.printStackTrace();
		}
	}
Exemplo n.º 26
0
 /**
  * Substracts the values from a previous object found in myList from the current Process in order
  * to obtain an object containing only the data since a referenc
  *
  * @param myList
  */
 public void substractFromRef(List<StatElement> myList) {
   if (myList != null) {
     for (int i = 0; i < myList.size(); i++) {
       try {
         Process myRef = (Process) myList.get(i);
         if ((this.getName().equals(myRef.getName())) && (this.getuid() == myRef.getuid())) {
           this.m_userTime -= myRef.getUserTime();
           this.m_systemTime -= myRef.getSystemTime();
           this.m_starts -= myRef.getStarts();
           if ((m_userTime < 0) || (m_systemTime < 0) || (m_starts < 0)) {
             Log.e(
                 TAG,
                 "substractFromRef generated negative values ("
                     + this.toString()
                     + " - "
                     + myRef.toString()
                     + ")");
           }
         }
       } catch (ClassCastException e) {
         // just log as it is no error not to change the process
         // being substracted from to do nothing
         Log.e(TAG, "substractFromRef was called with a wrong list type");
       }
     }
   }
 }
  public boolean onSavePassword(
      String schemePlusHost, String username, String password, Message resumeMsg) {
    // resumeMsg should be null at this point because we want to create it
    // within the CallbackProxy.
    if (Config.DEBUG) {
      junit.framework.Assert.assertNull(resumeMsg);
    }
    resumeMsg = obtainMessage(NOTIFY);

    Message msg = obtainMessage(SAVE_PASSWORD, resumeMsg);
    Bundle bundle = msg.getData();
    bundle.putString("host", schemePlusHost);
    bundle.putString("username", username);
    bundle.putString("password", password);
    synchronized (this) {
      sendMessage(msg);
      try {
        wait();
      } catch (InterruptedException e) {
        Log.e(LOGTAG, "Caught exception while waiting for onSavePassword");
        Log.e(LOGTAG, Log.getStackTraceString(e));
      }
    }
    // Doesn't matter here
    return false;
  }
Exemplo n.º 28
0
  public void ReDoORUndo(boolean flag) {
    if (!IsShowing) {
      ReDoOrUnDoFlag = true;
      try {
        if (flag) {
          Log.e("redo", "");
          ReDoNodes.add(pathNode.getTheLastNote());
          pathNode.deleteTheLastNote();
          preview(pathNode.getPathList());
          invalidate();
          //					ReDoOrUnDoFlag = true;
          //					if(!isShowing())
          //						preview(pathNode.getPathList());
        } else {
          Log.e("undo", "");
          pathNode.addNode(ReDoNodes.get(ReDoNodes.size() - 1));
          ReDoNodes.remove(ReDoNodes.size() - 1);
          preview(pathNode.getPathList());
          //					ReDoOrUnDoFlag = true;
          //					if(!isShowing())
          //						preview(pathNode.getPathList());
        }

      } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
        showCustomToast("无法操作=-=");
      }
    }
  }
Exemplo n.º 29
0
  // Update single ScavItem
  public void updateScavItem(ScavItem scavItem) {
    SQLiteDatabase db = this.getWritableDatabase();
    Log.d(TAG, db.toString());

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, scavItem.get_name()); // ScavItem name
    values.put(KEY_ADDRESS, scavItem.get_address()); // ScavItem address
    values.put(KEY_DIRECTIONS, scavItem.get_directions()); // ScavItem directions
    values.put(KEY_IMAGE, scavItem.get_image()); // ScavItem image

    // Update the corresponding row
    try {
      int i =
          db.update(
              TABLE_SCAV_ITEMS,
              values,
              KEY_ID + "=?",
              new String[] {String.valueOf(scavItem.get_id())});
      if (i <= 0) {
        Log.e(TAG, "Update failed in a weird way");
      }

    } catch (Exception e) {
      Log.e(TAG, "Update failed", e);
    }
    db.close();
  }
  public WebView createWindow(boolean dialog, boolean userGesture) {
    // Do an unsynchronized quick check to avoid posting if no callback has
    // been set.
    if (mWebChromeClient == null) {
      return null;
    }

    WebView.WebViewTransport transport = mWebView.new WebViewTransport();
    final Message msg = obtainMessage(NOTIFY);
    msg.obj = transport;
    synchronized (this) {
      sendMessage(obtainMessage(CREATE_WINDOW, dialog ? 1 : 0, userGesture ? 1 : 0, msg));
      try {
        wait();
      } catch (InterruptedException e) {
        Log.e(LOGTAG, "Caught exception while waiting for createWindow");
        Log.e(LOGTAG, Log.getStackTraceString(e));
      }
    }

    WebView w = transport.getWebView();
    if (w != null) {
      w.getWebViewCore().initializeSubwindow();
    }
    return w;
  }