Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 60

0
votes
answers
19 views
+10

如何在Android Volley Library中使用MultiPart上傳圖像文件陣列

0

我只是Android應用程序開發的初學者。如何在Android Volley Library中使用MultiPart上傳圖像文件陣列

我想使用Android Volley庫上傳圖像文件。

我已經用在一些博客的某個地方發現了這個輔助類:

public class VolleyMultiPartRequest extends Request<NetworkResponse> { 

    private final String twoHyphens = "--"; 
    private final String lineEnd = "
"; 
    private final String boundary = "apiclient-" + System.currentTimeMillis(); 

    private Response.Listener<NetworkResponse> mListener; 
    private Response.ErrorListener mErrorListener; 
    private Map<String, String> mHeaders; 

    SharedPreferencesManager sharedPreferencesManager =null; 

    public VolleyMultiPartRequest(int method, String url, 
            Response.Listener<NetworkResponse> listener, 
            Response.ErrorListener errorListener, Context context) { 
     super(method, url, errorListener); 
     this.mListener = listener; 
     this.mErrorListener = errorListener; 
     this.sharedPreferencesManager = new SharedPreferencesManager(context); 
    } 


    @Override 
    public Map<String, String> getHeaders() throws AuthFailureError { 
     Map<String, String> headers = new HashMap<String, String>(); 
     headers.put("Accept", "application/json"); 
     headers.put("Authorization", "Bearer " + sharedPreferencesManager.retreiveString(AppText.ACCESS_TOKEN)); 
     headers.put("Content-Type", "multipart/form-data"); 
     return headers; 
    } 
    @Override 
    public String getBodyContentType() { 
     return "multipart/form-data;boundary=" + boundary; 
    } 

    @Override 
    public byte[] getBody() throws AuthFailureError { 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     DataOutputStream dos = new DataOutputStream(bos); 

     try { 
      // populate text payload 
      Map<String, String> params = getParams(); 
      if (params != null && params.size() > 0) { 
       textParse(dos, params, getParamsEncoding()); 
      } 

      // populate data byte payload 
      Map<String, DataPart> data = getByteData(); 
      if (data != null && data.size() > 0) { 
       dataParse(dos, data); 
      } 

      // close multipart form data after text and file data 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      return bos.toByteArray(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 


    protected Map<String, DataPart> getByteData() throws AuthFailureError { 
     return null; 
    } 

    @Override 
    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) { 
     try { 
      return Response.success(
        response, 
        HttpHeaderParser.parseCacheHeaders(response)); 
     } catch (Exception e) { 
      return Response.error(new ParseError(e)); 
     } 
    } 

    @Override 
    protected void deliverResponse(NetworkResponse response) { 
     mListener.onResponse(response); 
    } 

    @Override 
    public void deliverError(VolleyError error) { 
     mErrorListener.onErrorResponse(error); 
    } 


    private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException { 
     try { 
      for (Map.Entry<String, String> entry : params.entrySet()) { 
       buildTextPart(dataOutputStream, entry.getKey(), entry.getValue()); 
      } 
     } catch (UnsupportedEncodingException uee) { 
      throw new RuntimeException("Encoding not supported: " + encoding, uee); 
     } 
    } 


    private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException { 
     for (Map.Entry<String, DataPart> entry : data.entrySet()) { 
      buildDataPart(dataOutputStream, entry.getValue(), entry.getKey()); 
     } 
    } 


    private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException { 
     dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); 
     dataOutputStream.writeBytes("Content-Disposition: form-data; name="" + parameterName + """ + lineEnd); 
     dataOutputStream.writeBytes(lineEnd); 
     dataOutputStream.writeBytes(parameterValue + lineEnd); 
    } 

    private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException { 
     dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); 
     dataOutputStream.writeBytes("Content-Disposition: form-data; name="" + 
       inputName + ""; filename="" + dataFile.getFileName() + """ + lineEnd); 
     if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) { 
      dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd); 
     } 
     dataOutputStream.writeBytes(lineEnd); 

     ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent()); 
     int bytesAvailable = fileInputStream.available(); 

     int maxBufferSize = 1024 * 1024; 
     int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     byte[] buffer = new byte[bufferSize]; 

     int bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

     while (bytesRead > 0) { 
      dataOutputStream.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     } 

     dataOutputStream.writeBytes(lineEnd); 
    } 

    public class DataPart { 
     private String fileName; 
     private byte[] content; 
     private String type; 

     public DataPart() { 
     } 

     public DataPart(String name, byte[] data) { 
      fileName = name; 
      content = data; 
     } 

     String getFileName() { 
      return fileName; 
     } 

     byte[] getContent() { 
      return content; 
     } 

     String getType() { 
      return type; 
     } 

    } 
} 

而且叫這個助手是這樣的:

VolleyMultiPartRequest volleyMultipartRequest = new VolleyMultiPartRequest(Request.Method.POST, Api.UPLOAD_FILE, 
       new Response.Listener<NetworkResponse>() { 
        @Override 
        public void onResponse(NetworkResponse response) { 
         try { 
          JSONObject obj = new JSONObject(new String(response.data)); 
          Toast.makeText(context, obj.getString("message"), Toast.LENGTH_SHORT).show(); 
          successCallBack.onSuccess(obj); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show(); 
         try { 
          errorCallBack.onError(new JSONObject("")); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, context) { 

      /* 
      * If you want to add more parameters with the image 
      * you can do it here 
      * here we have only one parameter with the image 
      * which is tags 
      * */ 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       Map<String, String> params = new HashMap<>(); 
       params.put("file_for", "post"); 
       params.put("file_type", "image"); 
       return params; 
      } 

      /* 
      * Here we are passing image by renaming it with a unique name 
      * */ 
      @Override 
      protected Map<String, DataPart> getByteData() { 
       Map<String, DataPart> params = new HashMap<>(); 
       long imagename = System.currentTimeMillis(); 
       params.put("images[]", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap))); 
       return params; 
      } 


     }; 

我收到服務器錯誤作爲響應。

我嘗試了不同的教程,但沒有找到確切的方法和簡單的解決方案。

在郵遞員中,郵件頭和參數是這樣的,有一個圖片數組,你可以在附圖中看到(8張照片)。我想用volley庫做完全相同的API調用。

enter image description here enter image description here

沙发
0
1

試試這個代碼:

我有類似的問題的種類我固定使用這個

上傳multiple files in array使用多

  1. 添加依賴條件

    compile 'org.apache.httpcomponents:httpcore:4.2.4' 
    compile 'org.apache.httpcomponents:httpmime:4.2' 
    compile 'com.mcxiaoke.volley:library:1.0.19' 
    

2.增加的gradle中

defaultConfig { 
      useLibrary 'org.apache.http.legacy' 

    } 
  • Helper類AndroidMultiPartEntity.java

    public class AndroidMultiPartEntity extends MultipartEntity 
    
    { 
    
        private final ProgressListener listener; 
    
        public AndroidMultiPartEntity(final ProgressListener listener) { 
         super(); 
         this.listener = listener; 
        } 
    
        public AndroidMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener) { 
         super(mode); 
         this.listener = listener; 
        } 
    
        public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary, 
                final Charset charset, final ProgressListener listener) { 
         super(mode, boundary, charset); 
         this.listener = listener; 
        } 
    
        @Override 
        public void writeTo(final OutputStream outstream) throws IOException { 
         super.writeTo(new CountingOutputStream(outstream, this.listener)); 
        } 
    
        public interface ProgressListener { 
         void transferred(long num); 
        } 
    
        public static class CountingOutputStream extends FilterOutputStream { 
    
         private final ProgressListener listener; 
         private long transferred; 
    
         public CountingOutputStream(final OutputStream out, 
                final ProgressListener listener) { 
          super(out); 
          this.listener = listener; 
          this.transferred = 0; 
         } 
    
         public void write(byte[] b, int off, int len) throws IOException { 
          out.write(b, off, len); 
          this.transferred += len; 
          this.listener.transferred(this.transferred); 
         } 
    
         public void write(int b) throws IOException { 
          out.write(b); 
          this.transferred++; 
          this.listener.transferred(this.transferred); 
         } 
        } 
    } 
    
  • API調用方法

    private class registerCall extends AsyncTask<Void, Integer, String> { 
    @Override 
    protected void onPreExecute() { 
        super.onPreExecute(); 
    } 
    
    @Override 
    protected void onProgressUpdate(Integer... progress) { 
    } 
    
    @Override 
    protected String doInBackground(Void... params) { 
        return registerMultipartCall(); 
    } 
    
    private String registerMultipartCall() { 
        String responseString = null; 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("URL"); //UPLOAD URL 
        try { 
         AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() { 
          @Override 
          public void transferred(long num) { 
          } 
         }); 
    
         File sourceFile = new File(filePath); 
         File sourceFile2 = new File(filePath); 
    
         entity.addPart("images[0]", new FileBody(sourceFile)); 
         entity.addPart("images[1]", new FileBody(sourceFile2)); 
         //Do your stuff multiple files 
    
         entity.addPart("file_type", new StringBody("image"); 
         entity.addPart("file_form", new StringBody("post"); 
    
         httppost.addHeader("Accept","application/json"); 
         httppost.addHeader("Content-Type", "multipart/form-data"); 
         httppost.addHeader("Authorization", "Bearer " + sharedPreferencesManager.retreiveString(AppText.ACCESS_TOKEN)); 
    
    
         httppost.setEntity(entity); 
    
         // Making server call 
         HttpResponse response = httpclient.execute(httppost); 
         HttpEntity r_entity = response.getEntity(); 
    
         int statusCode = response.getStatusLine().getStatusCode(); 
         if (statusCode == 200) { 
          // Server response 
          statusCode = 200; 
          responseString = EntityUtils.toString(r_entity); 
         } else { 
          statusCode = 200; 
          responseString = "Error occurred! Http Status Code: " + statusCode; 
         } 
    
        } catch (ClientProtocolException e) { 
         responseString = e.toString(); 
        } catch (IOException e) { 
         responseString = e.toString(); 
        } 
    
        return responseString; 
    
    } 
    
    @Override 
    protected void onPostExecute(String result) { 
        hideProgressDialog(); 
    
    } 
    

    }

  • 5.Calling異步

    new registerCall().execute(); 
    
    0
    votes
    answers
    21 views
    +10

    Android 4.0的啓動應用程序無法正常工作

    1

    IM有一個奇怪的問題,而不是在那裏一個URL應該啓動我的應用程序,它加載應用程序到瀏覽器本身,在這種情況下進入mozella!Android 4.0的啓動應用程序無法正常工作

    這裏是意圖過濾器我用我的應用程序如果有人能告訴我什麼即時做錯了。

    <uses-sdk android:minSdkVersion="15" /> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
    
    <application 
        android:name=".Globals" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" > 
        <activity 
         android:name=".RSS_ViewerActivity" 
         android:label="@string/app_name" > 
         <intent-filter> 
          <action android:name="android.intent.action.MAIN" /> 
          <category android:name="android.intent.category.LAUNCHER" /> 
         </intent-filter> 
    
         <intent-filter> 
           <action android:name="android.intent.action.VIEW" /> 
           <category android:name="android.intent.category.DEFAULT" /> 
           <data android:scheme="itpc" /> 
           <data android:scheme="pcast" /> 
           <data android:scheme="feed" /> 
           <data android:scheme="feeds" /> 
           <data android:scheme="rss" /> 
         </intent-filter> 
    
         <intent-filter> 
           <action android:name="android.intent.action.VIEW" /> 
           <category android:name="android.intent.category.DEFAULT" /> 
           <data android:mimeType="text/xml" android:scheme="http" /> 
           <data android:mimeType="application/rss+xml" android:scheme="http" /> 
           <data android:mimeType="application/atom+xml" android:scheme="http" /> 
           <data android:mimeType="text/xml" android:scheme="https" /> 
           <data android:mimeType="application/rss+xml" android:scheme="https" /> 
           <data android:mimeType="application/atom+xml" android:scheme="https" /> 
         </intent-filter> 
    
        </activity> 
        <activity android:name="RSSFeedActivity"></activity> 
        <activity android:name="com.CertificateAuthentication.Authenticator"></activity> 
    </application> 
    

    謝謝。

    UPDATE

    稍微多一些的信息,當對話框,詢問是否要選擇和應用,以打開彈出鏈接起來,它並不曾顯示我的應用程序,或任何與此有關。

    UPDATE

    我刪除了第二和第三意圖過濾器,我試圖將2個其餘意圖過濾器合併成1,但是這不加載來自瀏覽器的應用程序。上面的代碼是什麼樣子現在讓我相同的結果=前(這是煩人的,因爲它意味着用戶可以在應用程序運行的2次會議,一個從瀏覽器和一個從發射器。

    沙发
    0
    0

    你第二和第三<intent-filter>元素可能無法正常工作,因爲android:host未記錄支持通配符。這裏

    +0

    乾杯但是,不幸的是沒有工作=( 我試圖改變動作爲主,但不工作的對話框,詢問是否要選擇一個應用程序犯規不斷顯示我的應用程序! – 2012-08-13 13:44:15

    板凳
    0
    0

    問題是,這是轉義字符,所以讓你需要\這個表達式的工作。 Documentation clearly says,你需要使用\.爲點(有例如用\*)。

    我也同意CommonsWare答案,我在documentation這樣的表述已經發現:

    所有這些屬性是可選的,但它們不是獨立的 對方:對於權力是有意義的,一個方案還必須指定 。爲了使路徑有意義,必須指定方案和權威 。

    而且The host and port together constitute the URI authority所以在實踐中權力意味着主機所以你不能省略,顯然你不能把一個明星出現。

    IMO你讓它變得複雜,你不需要在這裏定義路徑! MIME類型應該做這項工作。嘗試找到一些讀取RSS的開源項目,看看他們如何定義清單。

    我想你需要類似的東西:

    <activity 
        android:name=".RSS_ViewerActivity" 
        android:label="@string/app_name" > 
        <intent-filter> 
         <action android:name="android.intent.action.MAIN" /> 
    
         <category android:name="android.intent.category.LAUNCHER" /> 
        </intent-filter> 
    
        <intent-filter> 
         <action android:name="android.intent.action.VIEW" /> 
         <category android:name="android.intent.category.BROWSABLE" /> 
         <category android:name="android.intent.category.DEFAULT" /> 
         <data android:scheme="itpc" /> 
         <data android:scheme="pcast" /> 
         <data android:scheme="feed" /> 
         <data android:scheme="feeds" /> 
         <data android:scheme="rss" /> 
         <data android:mimeType="text/xml" android:scheme="http" /> 
         <data android:mimeType="application/rss+xml" android:scheme="http" /> 
         <data android:mimeType="application/atom+xml" android:scheme="http" /> 
         <data android:mimeType="text/xml" android:scheme="https" /> 
         <data android:mimeType="application/rss+xml" android:scheme="https" /> 
         <data android:mimeType="application/atom+xml" android:scheme="https" /> 
        </intent-filter> 
    
    </activity> 
    
    +0

    感謝您的幫助,我拿出那些2個意圖過濾器,你和commonsware的建議,我已經更新了我上面的帖子。 我仍然會得到相同的結果,雖然=(我也嘗試過從另一個瀏覽器,股票安卓一,我得到的應用程序的相同結果從瀏覽器查看,而不是啓動/恢復,如果它是運行。 – 2012-08-14 08:25:34

    0
    votes
    answers
    18 views
    +10

    構建SQLite數據庫以分離可讀/寫數據

    1

    我正在編寫一個應用程序,允許用戶閱讀存儲在SQLite數據庫中的短篇小說。構建SQLite數據庫以分離可讀/寫數據

    到目前爲止這麼好。

    但是現在我想添加一些涉及寫入數據庫的功能(保存ScrollView的Y位置,以便用戶可以選擇它們離開的位置,爲書籤添加故事等)。

    我應該將這些值添加到books表,或者我應該創建一個單獨的表user_settings的列像id(INT),story_id(INT),y_position(INT),bookmarked(布爾)?

    注意:我也在考慮未來將故事存儲在非本地數據庫中的可能性。

    我的另一個問題是:我是否需要將數據庫移動到某個地方纔能寫入它?我使用的SQLiteAssetHelper和數據庫目前在/assets/databases/database.db。我聽到一些關於/data/data/mypackage文件夾的討論,但我無法在我的項目中看到它。

    我的數據庫設置爲當前如下:

    authors 
        id 
        name 
        name_alphanumeric 
    
    books 
        id 
        title 
        author_id 
        collection 
        body 
    

    如果它是有用的,這是我DatabaseHelper至今:

    public class DatabaseHelper extends SQLiteAssetHelper { 
    
        private static final int DATABASE_VERSION = 1; 
    
        private static final String DATABASE_NAME = "database9.db"; 
        private static final String BOOKS = "books"; 
        private static final String AUTHORS = "authors"; 
    
        public DatabaseHelper (Context context) { 
         super(context, DATABASE_NAME, null, DATABASE_VERSION); 
         // setForcedUpgrade(); 
        } 
    
        // Getting all books 
        public ArrayList<Author> getAllAuthors() { 
    
         ArrayList<Author> authorList = new ArrayList<>(); 
    
         // Select all query 
         String selectQuery = "SELECT id, name FROM " + AUTHORS + " ORDER BY name_alphabetic"; 
    
         SQLiteDatabase db = this.getWritableDatabase(); 
         Cursor cursor = db.rawQuery(selectQuery, null); 
    
         // looping through all rows and adding to list 
         if (cursor.moveToFirst()) { 
          do { 
           // create new author object 
           Author author = new Author(); 
           // set ID and name of author object 
           author.setID(Integer.parseInt(cursor.getString(0))); 
           author.setName(cursor.getString(1)); 
           // pass author object to authorList array 
           authorList.add(author); 
          } while (cursor.moveToNext()); 
         } 
    
         // return author list 
         return authorList; 
        } 
    
    
        // Getting all stories 
        public List<Book> getAllStories(int authorID) { 
    
         List<Book> storyList = new ArrayList<>(); 
    
         // Select all query 
         String selectQuery = "SELECT id, title FROM " + BOOKS + " WHERE author_id = " + authorID; 
    
         SQLiteDatabase db = this.getWritableDatabase(); 
         Cursor cursor = db.rawQuery(selectQuery, null); 
    
         // looping through all rows and adding to list 
         if (cursor.moveToFirst()) { 
          do { 
           Book book = new Book(); 
           book.setStoryID(Integer.parseInt(cursor.getString(0))); 
           book.setTitle(cursor.getString(1)); 
           storyList.add(book); 
          } while (cursor.moveToNext()); 
         } 
    
         // return contact list 
         return storyList; 
        } 
    
        // Get all collections 
        public List<Book> getAllCollections(int authorID) { 
    
         List<Book> collectionsList = new ArrayList<>(); 
    
         // Select all query 
         String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = " + authorID; 
         Log.i("stories", selectQuery); 
    
         SQLiteDatabase db = this.getWritableDatabase(); 
         Cursor cursor = db.rawQuery(selectQuery, null); 
    
         // looping through all rows and adding to list 
    
         if (cursor.moveToFirst()) { 
          do { 
           Book book = new Book(); 
           book.setCollection(cursor.getString(0)); 
           // Log.i("stories", cursor.getString(0)); 
           collectionsList.add(book); 
          } while (cursor.moveToNext()); 
         } 
    
         return collectionsList; 
         // not sure how to log collectionsList here 
        } 
    
        // Get story 
    
        public String getStoryBody(int storyID) { 
    
         // Log.i("stories", Integer.toString(storyID)); 
    
         String storyBody = ""; 
         // String storyBody(); 
    
         // Select all query 
         String selectQuery = "SELECT body FROM " + BOOKS + " WHERE id = " + storyID; 
    
         SQLiteDatabase db = this.getWritableDatabase(); 
         Cursor cursor = db.rawQuery(selectQuery, null); 
    
         // looping through all rows and adding to list 
         if (cursor.moveToFirst()) { 
          do { 
           storyBody = cursor.getString(0); 
          } while (cursor.moveToNext()); 
         } 
    
         return storyBody; 
        } 
    
        public int setScrollPosition(int scrollY, int storyID) { 
    
         String insertQuery = "UPDATE " + BOOKS + " SET scroll_position = " + scrollY + " WHERE id = " + storyID; 
         Log.i("insert", insertQuery); 
         SQLiteDatabase db = this.getWritableDatabase(); 
         db.execSQL(insertQuery); 
    
         return 0; 
    
        } 
    
        public int getScrollPosition(int storyID) { 
    
         int scrollPosition = 0; 
    
         String selectQuery = "SELECT scroll_position FROM " + BOOKS + " WHERE id = " + storyID; 
    
         SQLiteDatabase db = this.getWritableDatabase(); 
         Cursor cursor = db.rawQuery(selectQuery, null); 
    
         // looping through all rows and adding to list 
         if (cursor.moveToFirst()) { 
          do { 
           scrollPosition = cursor.getInt(0); 
          } while (cursor.moveToNext()); 
         } 
    
         return scrollPosition; 
    
        } 
    
    } 
    
    沙发
    0
    0

    但現在我想補充一點,涉及寫入功能數據庫 (保存ScrollView的Y位置,以便用戶可以從 中刪除,爲書籤添加故事等)。

    我應該將這些值添加到books表,或者我應該創建一個像ID(int)的列 單獨的表user_settings,story_id (INT),y_position(INT),書籤(布爾)?

    我想你已經明確表示,他們是USER值,因此它很可能是一個單獨的用戶表將是更好的更易於管理的解決方案。

    我的另一個問題是:我需要將數據庫移動到 能寫入它嗎?我正在使用SQLiteAssetHelper,目前數據庫爲 ,位於/assets/databases/database.db。我聽到一些關於 /data/data/mypackage文件夾的討論,但我在我的項目中看不到它。

    在所有likeliehood數據庫已被複制從資產文件夾到data/data/yourpackage/databases/dbfilenameSQLiteAssetHelper據我所知這主要就是它的功能。不過,我從來沒有使用過。)這樣的文件夾訪問有限(通常只有應用程序(紮根設備是一個例外)),所以很可能是爲什麼你看不到它。

    因此,寫入/更新數據庫的權限方式可能沒有任何要求。

    0
    votes
    answers
    15 views
    +10

    Height of status bar in Android

    What's the height of the status bar in Android? Is it always the same?

    From my measurements it seems that it's 25dp, but I'm not sure if it has the same height on all platforms.

    (I want to know this to properly implement a fade transition from an activity that doesn't have status bar to one that does)

    0
    votes
    answers
    26 views
    +10

    公共無效 - button.setEnabled與if語句我的情況?

    1
    public void onePointForTeamA(View v) { 
        if (foulCounterA == 5) { 
         scoreTeamA = scoreTeamA + 1; 
         scoreOnePointTeamA = scoreOnePointTeamA + 1; 
         displayForTeamA(scoreTeamA); 
         displayForTeamAOnePoint(scoreOnePointTeamA); 
        } 
    } 
    
    
    public void foulCountForTeamA(View v) { 
        if (foulCounterA < 5) 
         foulCounterA = foulCounterA + 1; 
        else 
         foulCounterA = 5; 
        displayForTeamAFoul(foulCounterA); 
    } 
    

    你好。首先,我對android開發和java很新。我爲這個問題搜索了很多東西,但是自己找不到解決方案。我想我還在學習。我發現的全部是關於重寫方法。
    關於我的問題;我想添加button.setEnabled(true);與「如果」我的Java文件,所以我的按鈕將只能點擊if (foulCounterA == 5),將無法點擊,否則。
    通過做這個改變,我想改變它的textView顏色,我知道該怎麼做。
    android:onClick="onePointForTeamA"
    android:onClick="foulCountForTeamA"關於XML文件。
    int scoreTeamA = 0;
    int scoreOnePointTeamA = 0;
    int foulCounterA = 0;關於Java文件。
    有什麼建議嗎?公共無效 - button.setEnabled與if語句我的情況?

    +0

    你有2種選擇。設置啓用(它在那裏,但不可點擊)或將其設置爲不可見(它在那裏,但沒有看到)? – Xenolion

    +0

    你喜歡哪種選擇? – Xenolion

    +0

    不可點擊。我希望它被看作是紅色的,我會在調整顏色之後做到這一點。 –

    沙发
    0
    0

    你應該知道的是,這種情況下的參數(View v)ButtonButtonView的一個子類。你可以投,如果你想你的方法裏面是

    Button button=(Button)v; 
    

    但您設置啓用或點擊行爲是不必要的。

    SOLUTION:

    添加行:如果你希望它被禁用,你可以把true爲啓用它

    v.setEnabled(false); 
    

    OR

    v.setClickable(false); 
    

    要設置它不可點擊,你可以把true爲它是點擊一次。

    +0

    我剛剛意識到我必須使用v.setEnabled類型的代碼,因爲我定義了它(View v)感謝。但是atm當我使用'v.setEnabled(false);'點擊一次後,它會禁用按鈕。當'(foulCounterB == 5)'這個要求達到時,我需要那個按鈕被解鎖而沒有點擊。 Atm爲了激活我再次點擊它,它會知道'(foulCounterB == 5)',但我無法點擊它,因爲我禁用了它。 –

    +0

    好吧我想我們可能不得不在代碼中添加一些新的邏輯,因爲當按鈕被禁用或不可點擊時,不會調用點擊方法!你能澄清整個應用程序的邏輯,以便我們可以一起解決它! – Xenolion

    +0

    謝謝你的幫助。我在開始時聲明瞭int值。 A隊有一個得分,它會用+3 +2 + 1得分(3個不同的按鈕)來計算這個得分。我做了代碼,好像faul按鈕沒有按下5次,+1分不會被激活。所以我'int scoreTeamA = 0;'在MainActivity下和許多public void onClick(View v)都改變了scoreTeamA。 –

    板凳
    0
    -1
    boolean condition = (foulCounterA == 5); 
    button.setEnabled(condition); 
    

    OR

    if(foulCounterA == 5) { 
        button.setEnabled(true); 
    } else { 
        button.setEnabled(false); 
    } 
    
    0
    votes
    answers
    14 views
    +10

    如何在Mac上找到Android SDK管理器路徑

    0

    我剛剛在Mac上下載了Android工作室,我只需要android sdk,但找不到從下載並直接下載Android studio的鏈接。如何在Mac上查找Android sdk路徑?如何在Mac上找到Android SDK管理器路徑

    沙发
    0
    0

    轉到文件 - >設置 - >系統設置 - > Android SDK中

    在頂部,你可以看到SDK位置

    0
    votes
    answers
    26 views
    +10

    我的getLocation方法總是返回null

    -4

    我正在製作一個應用程序來獲取用戶位置並將其顯示在Google地圖上,但由於getLocation方法返回null值,應用程序總是崩潰,任何人都可以告訴我什麼是問題?我的getLocation方法總是返回null

    的Manifest.xml

    <?xml version="1.0" encoding="utf-8"?> 
    
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.android.getyourlocation"> 
    
    <!-- 
        The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
        Google Maps Android API v2, but you must specify either coarse or fine 
        location permissions for the 'MyLocation' functionality. 
    --> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    
    <application 
        android:allowBackup="true" 
        android:icon="@mipmap/ic_launcher" 
        android:label="@string/app_name" 
        android:roundIcon="@mipmap/ic_launcher_round" 
        android:supportsRtl="true" 
        android:theme="@style/AppTheme"> 
    
        <!-- 
         The API key for Google Maps-based APIs is defined as a string resource. 
         (See the file "res/values/google_maps_api.xml"). 
         Note that the API key is linked to the encryption key used to sign the APK. 
         You need a different API key for each encryption key, including the release key that is used to 
         sign the APK for publishing. 
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        --> 
        <meta-data 
         android:name="com.google.android.geo.API_KEY" 
         android:value="@string/google_maps_key" /> 
    
        <activity 
         android:name=".MapsActivity" 
         android:label="@string/title_activity_maps"> 
         <intent-filter> 
          <action android:name="android.intent.action.MAIN" /> 
    
          <category android:name="android.intent.category.LAUNCHER" /> 
         </intent-filter> 
        </activity> 
    </application> 
    

    ,這是創建用戶

    package com.example.android.getyourlocation; 
    
    import android.Manifest; 
    import android.app.Service; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.content.pm.PackageManager; 
    import android.location.Location; 
    import android.location.LocationListener; 
    import android.location.LocationManager; 
    import android.os.Bundle; 
    import android.os.IBinder; 
    import android.support.v4.content.ContextCompat; 
    import android.util.Log; 
    
    /** 
    * Created by Hazem_Khaled on 2017-11-24. 
    */ 
    
    public class GpsManager extends Service implements LocationListener { 
    
    private final Context context; 
    protected LocationManager mLocationManager; 
    
    boolean isGpsEnabled; 
    boolean isNetworkEnable; 
    boolean canGetLocation; 
    
    Location mLocation; 
    
    public GpsManager(Context context) { 
        this.context = context; 
        this.isGpsEnabled=false; 
        this.isNetworkEnable=false; 
        this.canGetLocation=false; 
    
    } 
    
    public Location getLocation(){ 
        try { 
         mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); 
    
         //to find Location via GPS 
         String provider=LocationManager.GPS_PROVIDER; 
         isGpsEnabled=mLocationManager.isProviderEnabled(provider); 
    
         //to find Location via Network 
         provider=LocationManager.NETWORK_PROVIDER; 
         isNetworkEnable=mLocationManager.isProviderEnabled(provider); 
    
         if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
           || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
    
          //process to find Location via GPS 
          if(isGpsEnabled){ 
           if(mLocation == null){ 
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,10,this); 
            if (mLocationManager != null) 
             mLocation=mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
           } 
          } 
    
          //if mLocation still null this means that user location could not be found via GPS then we will use the Network to get user Location 
          if(mLocation == null){ 
           if(isNetworkEnable){ 
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,10,this); 
            if (mLocationManager != null) 
             mLocation=mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
           } 
          } 
         } 
        }catch (Exception e){ 
         Log.e("Error : ","in getLocation Method"); 
         e.printStackTrace(); 
        } 
        return mLocation; 
    } 
    
    public IBinder onBind(Intent intent) { 
        return null; 
    } 
    
    
    public void onLocationChanged(Location location) { 
    
    } 
    
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    
    } 
    
    public void onProviderEnabled(String provider) { 
    
    } 
    
    public void onProviderDisabled(String provider) { 
    
    } 
    

    }

    獲得位置我GpsManager.java類,這是我的MapsActivity.java

    package com.example.android.getyourlocation; 
    
    import android.location.Location; 
    import android.support.v4.app.FragmentActivity; 
    import android.os.Bundle; 
    
    import com.google.android.gms.maps.CameraUpdateFactory; 
    import com.google.android.gms.maps.GoogleMap; 
    import com.google.android.gms.maps.OnMapReadyCallback; 
    import com.google.android.gms.maps.SupportMapFragment; 
    import com.google.android.gms.maps.model.LatLng; 
    import com.google.android.gms.maps.model.MarkerOptions; 
    
    public class MapsActivity extends FragmentActivity implements 
    OnMapReadyCallback { 
    
    private GoogleMap mMap; 
    
    private Location mLocation; 
    private GpsManager mGpsManager; 
    
    double latitude; 
    double longitude; 
    
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_maps); 
    
        mGpsManager = new GpsManager(getApplicationContext()); 
        mLocation = mGpsManager.getLocation(); 
    
    
        latitude = mLocation.getLatitude(); 
        longitude = mLocation.getLongitude(); 
    
        // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
          .findFragmentById(R.id.map); 
        mapFragment.getMapAsync(this); 
    } 
    
    
    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
        mMap = googleMap; 
    
        // Add a marker in Sydney and move the camera 
        LatLng myLocation = new LatLng(latitude, longitude); 
        mMap.addMarker(new MarkerOptions().position(myLocation).title("I Am Here")); 
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation)); 
    } 
    

    }

    +3

    androidhive的另一個受害者所謂的教程 – Selvin

    +1

    https://stackoverflow.com/a/43082164/115145 – CommonsWare

    +0

    @Selvin這是肯定的。非常棒。 – ADM

    沙发
    0
    0

    有了新的API,你可以試試這個

    的build.gradle

    implementation 'com.google.android.gms:play-services-location:11.6.0' 
    

    GpsManager.java

    public class GpsManager extends LocationCallback { 
    
        private FusedLocationProviderClient client; 
        private Callback callback; 
    
        public interface Callback { 
         void onLocation(Location location); 
        } 
    
        public boolean start(Context context, Callback callback) { 
         this.callback = callback; 
         client = LocationServices.getFusedLocationProviderClient(context); 
         if (!checkLocationPermission(context)) return false; 
         client.requestLocationUpdates(getLocationRequest(), this, null); 
         return true; 
        } 
    
        public void stop() { 
         client.removeLocationUpdates(this); 
        } 
    
        @Override 
        public void onLocationResult(LocationResult locationResult) { 
         for (Location location : locationResult.getLocations()) { 
          callback.onLocation(location); 
         } 
        } 
    
        private boolean checkLocationPermission(Context context) { 
         int permissionCheck = ContextCompat.checkSelfPermission(
           context, android.Manifest.permission.ACCESS_FINE_LOCATION); 
         return permissionCheck == PackageManager.PERMISSION_GRANTED; 
        } 
    
        private LocationRequest getLocationRequest() { 
         return LocationRequest.create() 
           .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
           .setInterval(30_000L) 
           .setFastestInterval(20_000L); 
        } 
    } 
    

    ...一次這樣的連接到您的Activity ...

    MapsActivity.java

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GpsManager.Callback { 
    
        private static final int PERMISSION_REQUEST_FINE_LOCATION = 1; 
        private GpsManager mGpsManager; 
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
         ... 
         mGpsManager = new GpsManager(getApplicationContext(), this); 
    
         // check if user gave permissions, otherwise ask via dialog 
         if (!checkPermission()) { 
          getLocationPermissions(); 
          return; 
         } 
    
         mGpsManager.start(); 
         ... 
        } 
    
        @Override 
        protected void onStop() { 
         super.onStop(); 
         mGpsManager.stop(); 
        } 
    
        @Override 
        public void onLocation(Location location) { 
         // do something with your location 
        } 
    
        // CHECK PERMISSIONS PART 
    
        private boolean checkPermission() { 
         return isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)) && 
           isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)); 
        } 
    
        @TargetApi(Build.VERSION_CODES.M) 
        private void getLocationPermissions() { 
         requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 
           PERMISSION_REQUEST_FINE_LOCATION); 
        } 
    
        @Override 
        public void onRequestPermissionsResult(int code, @Nullable String permissions[], @Nullable int[] results) { 
         switch (code) { 
          case PERMISSION_REQUEST_FINE_LOCATION: 
           if (isPermissionGranted(results)) { 
            getLocationRequest(); 
           } 
         } 
        } 
    
        private boolean isPermissionGranted(int[] results) { 
         return results != null && results.length > 0 && isGranted(results[0]); 
        } 
    
        private boolean isGranted(int permission) { 
         return permission == PackageManager.PERMISSION_GRANTED; 
        } 
    } 
    

    現在,你必須確保在你的

    AndroidManifest.xml中

    所有權限
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    
    <uses-feature android:name="android.hardware.location.gps" /> 
    <uses-feature android:name="android.hardware.location.network" /> 
    

    希望它有幫助!

    板凳
    0
    0
    1. 嘗試更新谷歌Play服務

    2. 添加到搖籃,classpath 'com.google.android.gms:play-services-location:11.8.0'

    3. maven { url "https://maven.google.com" },添加此allprojects->倉庫內

    4. 添加implementation 'com.google.android.gms:play-services-location:11.8.0'內的build.gradle的依賴條件(Modeule.app)

    0
    votes
    answers
    10 views
    +10

    重新啓動一個任務活動

    3

    我有一個singleTask活動和我的應用程序supportsRtl,所以當我嘗試更改語言時,此SingleTask活動不受影響,因此我需要重新啓動它,任何幫助?重新啓動一個任務活動

    沙发
    0
    2

    如果您使用API?? 11以上,你可以使用:

    Activity.recreate() 
    

    如果需要支持較低API使用此再次調用您的活動:

    Intent i = getIntent(); 
    finish(); 
    startActivity(i); 
    
    板凳
    0
    0

    如果我們使用這種方法我們不需要重新開始活動

    用以下代碼更改您的應用語言:

    public static void notifyForLanguageChange(Context context, String languageCode) { 
         Resources res = context.getResources(); 
         // Change locale settings in the app. 
         DisplayMetrics dm = res.getDisplayMetrics(); 
         android.content.res.Configuration conf = res.getConfiguration(); 
         conf.locale = new Locale(languageCode.toLowerCase()); 
         res.updateConfiguration(conf, dm); 
        } 
    

    ,之後改變與(即重新加載字符串資源)

    public void setLabels() { 
         txtFirstView.setText(R.string.first); 
         txtSecondView.setText(R.string.second); 
         btnThirdView.setText(R.string.third); 
        } 
    
    屏幕標籤
    0
    votes
    answers
    23 views
    +10

    Android凌空不發送參數

    0

    不工作的代碼如下。看到這個代碼有什麼問題,爲什麼它沒有發送參數。我是Android新手。Android凌空不發送參數

    private void sendParams() 
    { 
        JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_Q_RECIPIES, 
          new Response.Listener<JSONArray>() { 
           @Override 
           public void onResponse(JSONArray response) { 
            Log.d(TAG, response.toString()); 
            hidePDialog(); 
    
            // Parsing json 
            for (int i = 0; i < response.length(); i++) { 
             try { 
    
              JSONObject obj = response.getJSONObject(i); 
              Recipie movie = new Recipie(); 
              movie.setRecipieName(obj.getString("recipie_name")); 
              movie.setId(obj.getInt("id")); 
              // build the image URL here 
              String s = AppConfig.URL_IMAGE + obj.getInt("id") + ".jpeg"; 
              movie.setImageURL(s); 
              movie.setPrimaryIngrediant(obj.getString("prim_ingr")); 
              movie.setUrl(obj.getString("url")); 
    
    
              // adding movie to movies array movie is nothing but recipie 
              movieList.add(movie); 
    
             } catch (JSONException e) { 
              e.printStackTrace(); 
             } 
    
            } 
    
            // notifying list adapter about data changes 
            // so that it renders the list view with updated data 
            adapter.notifyDataSetChanged(); 
           } 
          }, new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
    
          Log.e(TAG, "Filter error: " + error.getMessage()); 
          Toast.makeText(getApplicationContext(), 
            error.getMessage(), Toast.LENGTH_LONG).show(); 
          hidePDialog(); 
    
    
    
         } 
        }) { 
    
          @Override 
          protected Map<String, String> getParams() { 
           // Posting parameters to login url 
           Map<String, String> params = new HashMap<String, String>(); 
           params.put("ind_ajwain", Integer.toString(session.isAjwainChecked())); 
           //params.put("ind_asaftide", Integer.toString(session.isAsaftideChecked())); 
           params.put("rec_name", "chicken"); /// change this 
           params.put("ind_ginger", "0"); 
    
    
    
           //params.put("password", password); 
    
           return params; 
          } 
    
        }; 
        Log.d(TAG, movieReq.toString()); 
        //movieReq. 
    
        AppController.getInstance().addToRequestQueue(movieReq); 
    } 
    

    我跟着這個鏈接以獲得編碼唐:來源:https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/

    我還沒有做出上述太大的變化,唯一變化的參數。

    沙发
    0
    0

    您沒有通過new JsonArrayRequest中的任何請求方法。您必須通過Request.Method.POSTRequest.Method.GET

    +0

    默認情況下它是在[源代碼]'Method.GET'鹼(https://android.googlesource.com/platform/frameworks/volley/+/e7cdf98078bc94a2e430d9edef7e9b01250765ac/src/com/android/volley /toolbox/JsonArrayRequest.java)。由於OP沒有提供明確的問題背景,我現在不會考慮這個答案。 – Enzokie

    板凳
    0
    1

    要使用Volley向服務器發送數據,請參閱下面的代碼。

    Step1:使用POST方法發送數據。

    創建以下方法:

    private void makeJsonSend() { 
    
        StringRequest jsonObjReq = new StringRequest(Request.Method.POST,Const.ServiceType.URL, 
          new Response.Listener<String>() { 
    
           @Override 
           public void onResponse(String response) { 
            Log.e("response:forgot", response); 
            jsonParseResponse(response); 
           } 
    
          }, new Response.ErrorListener() { 
    
         @Override 
         public void onErrorResponse(VolleyError error) { 
    
    
          //show error message here 
         } 
        }) { 
    
         @Override 
         protected Map<String, String> getParams() throws AuthFailureError { 
          Map<String, String> params = new HashMap<String, String>(); 
          params.put("email","email"); 
    
          //pass parameter here 
    
          Log.i("request send data", params.toString()); 
    
          return params; 
         } 
    
    
         @Override 
         public Map<String, String> getHeaders() throws AuthFailureError { 
          HashMap<String, String> headers = new HashMap<>(); 
    
          //If you have header parameter then set here 
          return headers; 
         } 
    
    
        }; 
    
        AppController.getInstance().addToRequestQueue(movieReq); 
    
    } 
    

    步驟2:在這裏你必須得到該操作的響應響應方法。

    private void jsonParseResponse(String response) { 
    
        try { 
         JSONObject jsonObject = new JSONObject(response); 
    
         if (jsonObject.getString("status").equals("200")) { 
    
          cc.showToast(jsonObject.getString("message")); 
    
    
    
    
         } else { 
    
          cc.showToast(jsonObject.getString("message")); 
         } 
    
        } catch (JSONException e) { 
         e.printStackTrace(); 
         Log.e("Forgot Error",e.toString()); 
        } 
    
    } 
    
    +0

    也與此代碼發生同樣的事情。 – user1130456

    +0

    你有沒有在Postman中檢查Webservice? –

    16
    votes
    answers
    18 views
    +10

    set up device for development (???????????? no permissions)

    I am using a Samsung galaxy nexus phone (Android 4.0 platform) .

    I am developing Android app on Ubuntu linux OS. I would like to run my application directly on the Samsung handset device, so I performed the following setup steps:

    1. in my project AndroidManifest.xml file, added android:debuggable="true" to the <application> element

    2. On the device, in the Settings > Security enabled Unknown sources

    3. On the device, in the Settings > Developer options enabled USB debugging

    4. On my computer, created the /etc/udev/rules.d/51-android.rules file with the following content:

      SUBSYSTEM=="usb", ATTR{idVendor}=="04E8", MODE="0666", GROUP="plugdev" 
      
    5. On my computer, run the chmod a+r /etc/udev/rules.d/51-android.rules command

    Then, on my computer I opened a terminal and executed the adb devices command, I got:

    List of devices attached 
    ????????????    no permissions
    

    Since I did not see my device but only ???????????? no permissions, I then run the following commands:

     adb kill-server
     adb start-server
     adb devices
    

    But I still got:

    List of devices attached 
    ????????????    no permissions
    

    Why? What am I missing?

    沙发
    +40

    I know this might be a little late but here is a very good article on how to manually add Android ADB USB Driver. Manually adding Android ADB USB driver in Ubuntu 14.04 LTS

    Edited to Add Link Content

    Steps

    Note: Make sure that you have connected your Android device in USB Debugging mode

    Open terminal (CTRL + ALT + T) and enter command: lsusb

    Now you might get a similar reply to this:
    Bus 002 Device 013: ID 283b:1024

    Note: With reference to this Bus 002 Device 008: ID 283b:1024
    {idVendor}==”283b” {idProduct}==”1024″

    Now enter the following command: sudo gedit /etc/udev/rules.d/51-android.rules
    This creates the android rules file (51-android.rules) or open the existing one in the specified location (/etc/udev/rules.d)

    Add a new line to this file:
    SUBSYSTEM==”usb”, ATTRS{idVendor}==”283b”, ATTRS{idProduct}==”1024″, MODE=”0666″

    Note Edit idVendor & idProduct values with your device values. Save and close.

    Now enter the following command:
    sudo chmod a+rx /etc/udev/rules.d/51-android.rules - grant read/execution permission
    sudo service udev restart - Restart the udev service

    Now we have to add the idVendor to adb_usb.ini. Enter the following commands:
    cd ~/.android
    gedit adb_usb.ini

    Add the following value 0x283b

    This is nothing but 0x(idVendor value). So replace the value with. respect to your device value Save and close the file.

    Now enter the following command:
    sudo service udev restart

    Plug out the Android device and reconnect it again.
    Now enter the following command:
    adb kill-server
    adb devices

    There you go! Your device must be listed.

    Copied From Manually adding Android ADB USB driver in Ubuntu 14.04 LTS

    Worked for me.

    @bummi謝謝。 - dc-aoxn 2015年6月20日10:57

    謝謝@czprobity。好像我每隔幾個月就回到這裡......這也適合我,但我認為你可能需要在'adb kill-server'之後'adb start-server' - 史蒂文史密斯2017年1月6日2:51

    板凳
    +40

    I had the same problem with my Galaxy S3. My problem was that the idVendor value 04E8 was not the right one. To find the right one connect your smartphone to the computer and run lsusb in the terminal. It will list your smartphone like this:

    Bus 002 Device 010: ID 18d1:d002 Google Inc.
    

    So the right idVendor value is 18d1. And the line in the /etc/udev/rules.d/51-android.rules has to be:

    SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev" 
    

    Then I run sudo udevadm control --reload-rules and everything worked!

    你有沒有意思:ATTR {idVendor} ==“18d1” - Tanasis於17年7月27日在20:04

    地板
    +20
    1. Follow the instructions at http://developer.android.com/guide/developing/device.html
    2. Replace the vendor id of “0bb4″ with “18d1″ in /etc/udev/rules.d/51-android.rules. Or add another line that reads: SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"
    3. restart computer or just restart udev service.

    上面的鏈接現在被打破 - codecowboy 17年7月30日在8:37

    4楼
    +20

    Use the M0Rf30/android-udev-rules GitHub community maintained udev-rules

    https://github.com/M0Rf30/android-udev-rules/blob/master/51-android.rules

    This is the most complete udev-rules list I've seen so far, even more than the currently recommended sudo apt-get install android-tools-adb on the official documentation, and it solved that problem for me.

    當一條規則適用於所有人時,為什麼還要“維護列表”呢?stackoverflow.com/a/45006231/1778421 - 亞歷克斯P. 18年10月21日21:54

    @AlexP。謝謝我不知道那個方法。不知道為什麼官方指南不反對這一點嗎? - Ciro Santilli新疆改造中心996ICU六四事件於2017年10月21日21:59

    由於懶惰和知識慣性多數。最初的Android開發人員使用具有相同供應商ID的設備,因此他們採用了他們能想到的最簡單的方法。當更多供應商創建更多設備時 - 開發人員只是不斷向規則文件添加更多ID。 - Alex P. 18年7月19日17:43

    5楼
    +10

    When you restart udev, kill adb server & start adb server goto android sdk installation path & do all on sudo. then run adb devices it will solve permission problem.

    6楼
    +10

    My device is POSITIVO and my operational system is Ubuntu 14.04 LTS So, my problem was in variable name

    I create the file /etc/udev/rules.d/51-android.rules and put SUBSYSTEM=="usb", SYSFS{idVendor}=="1662", MODE="0666"

    I disconnected device and execute:

    $ sudo udevadm control --reload-rules
    $ sudo service udev restart
    

    after this i connected the android device in developer mode again and

    $ adb devices
    
    List of devices attached 
    1A883XB1K   device
    
    7楼
    +10

    Without unplugging

    All the provided answers assume that you are able to unplug and reconnect the USB cable. In situations where this is not possible (e.g., when you are remote), you can do the following to essentially do what the suggested udev rules would do on re-plug:

    lsusb
    

    Find the device you care about, e.g.:

    Bus 003 Device 005: ID 18d1:4ee4 Google Inc. Nexus
    

    Take note of the bus number it is on and then execute, e.g. for bus 003:

    sudo chmod a+w /dev/bus/usb/003/*
    

    Clearly this may be more permissive than you want (there may be more devices attached than just this one), but you get the idea.

    要在不重新連接設備的情況下應用新的udev規則,只需使用udevadm trigger --verbose --action = add --subsystem-match = usb命令。 - Alex P. 17年7月10日在7:22

    非常好!@AlexP。 - Christian Fritz於17年7月11日17:39

    8楼
    +10

    You should NOT run adb server as root as other answers are suggesting. Instead if you are using Arch Linux do the following:

    1. Install the android-udev package with Pacman
    2. Reload udev rules:

      # udevadm control --reload-rules
      
    3. Add yourself to adbusers group and then logout and login:

      # usermod -aG adbusers $LOGNAME
      

    Source: https://wiki.archlinux.org/index.php/android#Configuring_adb

    9楼
    0

    Try instead of GROUP="plugdev" use the main group of your user.

    我使用我的用戶名,它沒有幫助 - Leem.fin 12月9日12:09

    10楼
    0

    Please DO NOT follow solutions suggesting to use sudo (sudo adb start-server)! This run adb as root (administrator) and it is NOT supposed to run like that!!! It's a BAD workaround!

    Everything running as root can do anything in your system, if it creates or modify a file can change its permission to be only used by root. Again, DON'T!

    The right thing to do is set up your system to make the USER have the permission, check out this guide i wrote on how to do it properly.

    11楼
    -10

    In my case on ubuntu 12.04 LTS, I had to change my HTC Incredible usb mode from charge to Media and then the device showed up under adb. Of course, debugging was already on in both cases.

    12楼
    -10

    I used su and it started working. When I use Jetbrains with regular user, I see this problem but after restarting Jetbrains in su mode, I can see my device without doing anything.

    I am using Ubuntu 13.04 and Jetbrains 12.1.4

    13楼
    -10

    You could also try editing adb_usb.ini file, located at /home/username/.android/. This file contains id vendor list of devices you want to connect. You just add your device's id vendor in new line (it's one id per line). Then restart adb server and replug your device.

    It worked for me on Ubuntu 12.10.

    14楼
    -10

    Anyway, what I did to solve this problem(on Ubuntu).

    1. Defined in what cases I need to run these commands. For most ubuntu users there is a home folder (hidden file .bashrc).

      In which you can record the launch of these commands. But these commands will be triggered when you enter the bash command in the console.

    2. Since I have a shell .zshrc then I did the following:

      open console: gedit .zshrc

    When the file opens, add the following line:

    ./.add_device_permissions.sh
    

    After or before, we need to create this file: .add_device_permissions.sh in which we write the following:

    #!/bin/bash
    # Add permissions
    ADB="/home/vadimm/Android/Sdk/platform-tools/adb"
    $ADB devices
    $ADB kill-server
    cat .permissions_redmi_note | sudo -S $ADB devices
    $ADB kill-server
    cat .permissions_redmi_note | sudo -S $ADB devices
    

    Also we need create .permissions_redmi_note where we need to hardcode our password.

    1. Not to add to the file .zshrc unnecessary we can specify the path when starting the system itself: Startup Applications Preferences

    Where we press on "Add" and write our command: /home/vadimm/.add_device_permissions.sh

    1. Also u can tried use in command line next commands: ./adb devices ./adb kill-server sudo ./adb devices ./adb kill-server ./adb devices
    15楼
    -20

    If anyone faces the following error message when they use adb devices

    no permissions (verify udev rules); see [http://developer.android.com/tools/device.html]
    

    Execute the following

    sudo -s 
    adb kill-server
    adb start-server
    

    That fixed the issue for me on a custom build android device