我正在尝试捕获数据库中存在的图像路径,并动态推送到变量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<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:FATAL EXCEPTION:main 处理:com.clubee.vote,PID:26927 android.os.NetworkOnMainThreadException 在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) 在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 在com.clubee.vote.JSONParser.makeHttpRequest(JSONParser.java:64) 在com.clubee.vote.CarregaEnquete $ PesquisaEnqueteDetalhes $ 1.run(CarregaEnquete.java:182) 在android.os.Handler.handleCallback(Handler.java:733) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:212) 在android.app.ActivityThread.main(ActivityThread.java:5135) at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invoke(Method.java:515) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:878) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 在dalvik.system.NativeStart.main(本地方法)
答案 0 :(得分: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方法中的UI