2015-03-25 74 views
0

我試圖捕獲數據庫中存在的圖像路徑,並動態推送到變量URL。每次我將該應用程序稱爲「新的PesquisaEnqueteDetalhe().exec(url);」時,應用程序停止響應並關閉。動態填充圖像url路徑並將其推送到ImageView

我已經重寫過好幾次了,仍然沒有找到我錯的地方。我在同一個應用程序中完成了類似的場景。可以幫助我嗎?

我的Java類

package com.clubee.vote; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.net.wifi.WifiManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.List; 


public class CarregaEnquete extends Activity { 

String pid="1"; 
String url; 
TextView txtNome; 


private static final String TAG_SUCCESS = "success"; 
private static final String TAG_ENQUETE = "nome_votacao"; 
private static final String TAG_URL = "url_img_path"; 


private static String url_Insere_voto = "http://dev.clubee.com.br/dbvote/insereVoto.php"; 
private static String url_PesquisaEnquete = "http://dev.clubee.com.br/dbvote/pesquisaDetalhesEnquete.php"; 

JSONParser jsonParser = new JSONParser(); 

private ProgressDialog pDialog; 

public String tipoVoto=null; 

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

    new PesquisaEnqueteDetalhes().execute(url); 

    int loader = R.drawable.loader; 
    ImageView image = (ImageView) findViewById(R.id.imgVotacao); 
    String image_url = url; 
    //String image_url = "http://clubee.com.br/imgs/vote_imgs/DilmaEdicao.png"; 
    ImageLoader imgLoader = new ImageLoader(getApplicationContext()); 
    imgLoader.DisplayImage(image_url, loader, image); 

    final Button btnVotoSim = (Button) findViewById(R.id.btnSim); 
    final Button btnVotoNao = (Button) findViewById(R.id.btnNao); 

    // evento de clique no botao Sim 
    btnVotoSim.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 

      Button btnSim = (Button) findViewById(R.id.btnSim); 
      String tipoVotoS = btnSim.getText().toString(); 
      tipoVoto = tipoVotoS; 
      new InsereVoto().execute(); 
     } 
    }); 

    // evento de clique no botao Nao 
    btnVotoNao.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 

      Button btnNao = (Button) findViewById(R.id.btnNao); 
      String tipoVotoN = btnNao.getText().toString(); 
      tipoVoto = tipoVotoN; 
      new InsereVoto().execute(); 
     } 
    }); 

} 

class InsereVoto extends AsyncTask<String, String, String> { 

    /** 
    * Antes de inserir e iniciar as açoes de background essa thread mostra o progresso 
    * */ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(CarregaEnquete.this); 
     pDialog.setMessage("Inserindo Voto.."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... args) { 

     WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
     String macAddress = wfman.getConnectionInfo().getMacAddress(); 
     if (macAddress == null) { 
      macAddress = "Dispositivo sem endereço mac"; 
     } 

     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tipoVoto", tipoVoto)); 
     params.add(new BasicNameValuePair("macAddress", macAddress)); 

     // getting JSON Object 
     // Note that create product url accepts POST method 
     JSONObject json = jsonParser.makeHttpRequest(url_Insere_voto, "POST", params); 

     // check log cat from response 
     Log.d("Create Response", json.toString()); 

     // check for success tag 
     try { 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // Voto cadastrado com sucesso 
       Intent i = new Intent(getApplicationContext(), Resultado.class); 
       startActivity(i); 

      } else { 
       // Voto não registrado 
       Intent i = new Intent(getApplicationContext(), ResultadoFalho.class); 
       startActivity(i); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    protected void onPostExecute(String file_url) { 

     pDialog.dismiss(); 
    } 

} 

class PesquisaEnqueteDetalhes extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(CarregaEnquete.this); 
     pDialog.setMessage("Buscando detalhes. Aguarde..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... params) { 

     // updating UI from Background Thread 
     runOnUiThread(new Runnable() { 
      public void run() { 
       // Check for success tag 
       int success; 
       try { 
        // Building Parameters 
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        params.add(new BasicNameValuePair("pid", pid)); 

        // getting product details by making HTTP request 
        // Note that product details url will use GET request 
        JSONObject json = jsonParser.makeHttpRequest(
          url_PesquisaEnquete, "GET", params); 

        // check your log for json response 
        Log.d("Single Product Details", json.toString()); 

        // json success tag 
        success = json.getInt(TAG_SUCCESS); 
        if (success == 1) { 
         // successfully received product details 
         JSONArray enqueteObj = json 
           .getJSONArray(TAG_ENQUETE); // JSON Array 

         // get first product object from JSON Array 
         JSONObject enquete = enqueteObj.getJSONObject(0); 

         // product with this pid found 
         // Edit Text 
         txtNome = (TextView) findViewById(R.id.infoVotacao); 

         // display product data in EditText 
         txtNome.setText(enquete.getString(TAG_ENQUETE)); 
         url = (enquete.getString(TAG_URL)); 

        }else{ 
         // product with pid not found 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

     return url; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog once got all details 
     pDialog.dismiss(); 
     } 
    } 
} 

和XML。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#fffcfffa" 
tools:context=".CarregaEnquete"> 

<ImageView 
    android:id="@+id/imgLogo" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="top" 
    android:scaleType="fitCenter" 
    android:adjustViewBounds="true" 
    android:src="@drawable/bkg_app" /> 

<TextView 
    android:id="@+id/infoVotacao" 
    style="@style/CodeFont" 
    android:layout_below="@id/imgLogo"/> 

<ImageView 
    android:id="@+id/imgVotacao" 
    android:layout_width="300dp" 
    android:layout_height="300dp" 
    android:layout_below="@+id/infoVotacao" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="10dp" /> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:layout_alignParentBottom="true" 
    android:gravity="bottom"> 

    <Button 
     android:id="@+id/btnSim" 
     android:layout_width="0.0dip" 
     android:layout_height="wrap_content" 
     android:text="SIM" 
     android:textColor="#FFFFFF" 
     android:layout_weight="1.0" 
     android:background="@drawable/votebtngreen_btn_default_holo_light"/> 

    <Button 
     android:id="@+id/btnNao" 
     android:layout_width="0.0dip" 
     android:layout_height="wrap_content" 
     android:text="NÃO" 
     android:textColor="#FFFFFF" 
     android:layout_weight="1.0" 
     android:background="@drawable/votebtnred_btn_default_holo_light"/> 

</LinearLayout> 

輸出,在Android Studio,請複製下面

03-24 21:57:32.376 26927-26927/com.clubee.vote E/AndroidRuntime:致命異常:主 工藝:com.clubee.vote,PID:26927 android.os.NetworkOnMainThreadException 在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1154) 在java.net.InetAddress.lookupHostByName(InetAddress的。 Ĵ (InetAddress.java:214) (位於org.apache.http.impl.conn.DefaultClientConnectionOperator)。 openConnection(DefaultClientConnectionOperator.java:141) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java: 119) 在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 在有機apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) at com.clubee.vote.JSONParser.makeHttpRequest(JSONParser.java:64) at com.clubee.vote.CarregaEnquete $在Android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper .loop(Looper.java:212) at android.app.ActivityThread.main(ActivityThread.java:5135) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method。調用(Method.java:515) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:878) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 在dalvik.system.NativeStart.main(本機方法)

回答

0

你的問題就在這裏:

protected String doInBackground(String... params) { 

    // updating UI from Background Thread 

    runOnUiThread(new Runnable() { 
     public void run() { 
      // Check for success tag 
      int success; 
      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("pid", pid)); 

       // getting product details by making HTTP request 
       // Note that product details url will use GET request 
       JSONObject json = jsonParser.makeHttpRequest(
         url_PesquisaEnquete, "GET", params); 

您正在AsyncTask的背景部分中運行此操作,但隨後將其包裝在runOnUIThread()runnable中。這使得你的AsyncTask幾乎無用,因爲它不再在後臺線程上運行。

你或許可以去除runOnUIThread()塊,並把所有必要的代碼,以更新postExecute方法

+0

甚至進行更改的UI,問題仍然存在。我的腦海裏還沒有任何東西。 – Barcat 2015-03-25 16:25:30

+0

發佈您的更新代碼。 – 2015-03-25 18:51:55

+0

你好加里,我對我的代碼做了一些修改,現在它運行沒有問題。你的建議幫助我解決了這個問題,但是我做了一點不同。 – Barcat 2015-03-26 13:30:28