动态地填写图像的URL路径并将其推送到ImageView。

22 浏览
0 Comments

动态地填写图像的URL路径并将其推送到ImageView。

我正在尝试捕捉存在数据库中的图像路径,并动态将其推送到变量URL。 每次调用应用程序“new PesquisaEnqueteDetalhe()。execut(url);”时,应用程序停止响应并关闭。

我已经重写了几次,但仍然没有找到我的错误所在。 我在同一个应用程序中做了类似的情况。 你能帮帮我吗?

我的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 params = new ArrayList();
        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 params = new ArrayList();
                    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。




    

在Android Studio的输出如下所示

03-24 21:57:32.376 26927-26927/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: main

Process: com.clubee.vote, PID: 26927

android.os.NetworkOnMainThreadException

at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1154)

at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)

at java.net.InetAddress.getAllByName(InetAddress.java:214)

at 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)

at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

at org.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$PesquisaEnqueteDetalhes$1.run(CarregaEnquete.java:182)

at 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.invoke(Method.java:515)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

at dalvik.system.NativeStart.main(Native Method)

admin 更改状态以发布 2023年5月24日
0
0 Comments

你的问题就在这里:

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 params = new ArrayList();
                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()的可运行对象中。这使得你的AsyncTask几乎无用,因为它不再在后台线程上运行。

你可以移除runOnUIThread()代码块,并将所有必要的更新UI的代码放入postExecute方法中。

0