2011-01-24 13 views
6

Saluti,Android: caricare foto

Ho problemi a caricare una foto dal mio telefono Android. Ecco il codice che sto usando per richiedere all'utente di selezionare una foto:

public class Uploader{ 
     public void upload(){ 
      Log.i("EOH","hi..."); 
      Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT); 
      photoPickerIntent.setType("image/*"); 
      startActivityForResult(photoPickerIntent, 1); 
     } 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) 
     { 
      if (resultCode == RESULT_OK) 
      { 
       Bundle extras = data.getExtras(); 
       Bitmap b = (Bitmap) extras.get("data"); 
       //what do do now with this Bitmap... 
        //how do I upload it? 




      } 
     } 

    } 

così ho il Bitmap b, ma non so che cosa fare dopo?

ho il seguente codice per l'invio di richieste POST:

List<NameValuePair> params = new ArrayList<NameValuePair>(2); 
params.add(new BasicNameValuePair("someValA", String.valueOf(lat))); 
params.add(new BasicNameValuePair("someValB", String.valueOf(lng))); 
new HttpConnection(handler).post("http://myurl.com/upload.php",params); 

Come posso collegare un'immagine bitmap a questo? Ho cercato google per anni e non riesco a trovare un buon modo di farlo.

Spero che qualcuno possa aiutare.

Molte grazie in anticipo,


Ok Ho provato il suggerimento Chirag Shah. Qui è il mio codice:

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
     { 
      if (resultCode == RESULT_OK) 
      { 
       Uri imageUri=data.getData(); 
       List<NameValuePair> params = new ArrayList<NameValuePair>(1); 
       params.add(new BasicNameValuePair("image", imageUri.getPath())); 
       post("http://www.myurl.com/ajax/uploadPhoto.php",params); 
      } 
     } 

dove la funzione posta (come raccomandato) è:

public void post(String url, List<NameValuePair> nameValuePairs) { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpPost httpPost = new HttpPost(url); 

      try { 
       MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

       for(int index=0; index < nameValuePairs.size(); index++) { 
        if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) { 
         // If the key equals to "image", we use FileBody to transfer the data 
         entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue()))); 
        }else{ 
         // Normal string data 
         entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); 
        } 
       } 

       httpPost.setEntity(entity); 

       HttpResponse response = httpClient.execute(httpPost, localContext); 
       Log.i("EOH",response.toString()); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
    } 

Tuttavia myurl.com/ajax/uploadPhoto.php sta ottenendo nulla. Ho creato un registro PHP per registrare qualsiasi attività su uploadPhoto.php e non viene mostrato nulla. Vale la pena notare che se digito semplicemente myurl.com/ajax/uploadPhoto.php direttamente in un browser Web, viene registrato correttamente.

Altri suggerimenti?

Molte grazie,

+0

ho trovato che i post http devono essere eseguiti da un'attività asincrona altrimenti non accadrà. Ho cercato di fare qualcosa di simile sia postare e ottenere dati e necessario per avvolgere i messaggi per l'url in un compito asincrono. (http://developer.android.com/reference/android/os/AsyncTask.html) – Tim

risposta

0

Se non lo siete già. Prova a inserire il post sul server in un'attività Async e a chiamare l'attività. Ho scoperto che l'API che sto usando richiede post http/deve essere fatto lontano dal thread principale per evitare possibili problemi che bloccano il thread principale.

È stato relativamente semplice impostarlo come attività Async e ha iniziato a funzionare.

Maggiori informazioni su compiti asincroni: http://developer.android.com/reference/android/os/AsyncTask.html

Per un semplice esempio, questo è uno dei miei compiti asincrone:

private class SomeAsyncTask extends AsyncTask<String, Void, JSONObject> { 

    @Override 
    protected JSONObject doInBackground(String... arg0) { 

     UserFunctions uf = new UserFunctions(); 
     JSONObject res = uf.doPostToServer(arg0[0], arg0[1], arg0[2], getApplicationContext()); 

     return res; 
    } 

    @Override 
    protected void onPostExecute(JSONObject result) { 

     try { 
      int success = result.getInt("success"); 
      if(success == 1) { 

       Intent vcact = new Intent(getApplicationContext(), OtherActivity.class); 
       vcact.putExtra("id", cid); 
       startActivity(vcact); 
       // close main screen 
       finish(); 

      } else { 
       Toast.makeText(SomeActivity.this, "Error saving to server. Try again.", Toast.LENGTH_SHORT).show(); 
      } 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
} 

e si chiama onclick con

new SomeAsyncTask().execute(cid, otherdata, moredata); 
+0

Il post effettivo è fatto in uf.doPostToServer ... Penso che tu sia sulla strada giusta, basta provare a renderlo asincrono e vedere se aiuta. Lo ha fatto per me. – Tim

Problemi correlati