0

您好,我是 android 开发新手,这是我的第一个应用程序。我尝试连接到数据库,但是当模拟器启动时,应用程序意外停止。eclipse中的一切都很好,但是当我运行模拟器时它会停止。这是代码:

public class Antallaktika extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null; 
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
String targetname;
String targetsku;
String targetprice;
int responseCode;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.antallaktika);
    setTitle("Ανταλλακτικά");

    try {
        URL url = new URL("http://machina.gr/antallaktika.php");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(2000);
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        responseCode = httpConnection.getResponseCode();
    }
    catch (Exception e) {} 
    try{
        if(isNetworkAvailable()==true  && responseCode == HttpURLConnection.HTTP_OK){
            new LoadData().execute();
        }
        else{
            AlertDialog.Builder ad=new AlertDialog.Builder(this);
            ad.setMessage("No Internet Connection available!!!");
            ad.show();
        }
    }
    catch(Exception e){

    }
}

public class LoadData extends AsyncTask<Void, Void, Void> { 
    private ProgressDialog progressDialog;  
    @Override
    // can use UI thread here
    protected void onPreExecute() {
    this.progressDialog = ProgressDialog.show(Antallaktika.this, ""," Loading...");  
    }
    @Override
    protected void onPostExecute(final Void unused) {  
         this.progressDialog.dismiss(); 
        try{
                 ListView listview = (ListView) findViewById(R.id.listView1);  
                this.progressDialog.dismiss();  
                 listview.setAdapter(new DataAdapter(Antallaktika.this,al.toArray(new String[al.size()]),al1.toArray(new String[al1.size()]),al2.toArray(new String[al2.size()])));

            }
            catch(Exception e){

                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            } 

    }

    @Override
    protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub  
        // HTTP post

                try {

                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    HttpClient httpclient = new DefaultHttpClient(); 
                    try{
                    HttpPost httppost = new HttpPost("http://machina.gr/antallaktika.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    }
                    catch(Exception e){
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }
                    //buffered reader
                    try{
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 80);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line = "0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                    }
                    catch(Exception e){
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }
                    try{
                    jArray = new JSONArray(result);
                    JSONObject json_data = null;
                    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i); 
                        targetname=json_data.getString("targetname");
                        targetsku=json_data.getString("targetsku");
                        targetprice = json_data.getString("targetprice"); 
                        al.add(targetname); 
                        al1.add(targetsku);
                        al2.add(targetprice);  
                    }
                }
                    catch(JSONException e){
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }   
                    } catch (ParseException e) {
                    //  Log.e("log_tag", "Error in http connection" + e.toString());
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }  
                     catch (Exception e) {
                            //  Log.e("log_tag", "Error in http connection" + e.toString());
                                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                            }       


            return null;

        }
    }

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null, otherwise check
        // if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {

            // Log.i("net status:", "Online...!!!");
            return true;
        }
        // Log.i("net status:", "offline...!!!");
        return false;

}

}

logcat 是:

08-01 20:51:36.042: E/AndroidRuntime(375): FATAL EXCEPTION: AsyncTask #1
08-01 20:51:36.042: E/AndroidRuntime(375): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 20:51:36.042: E/AndroidRuntime(375):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.lang.Thread.run(Thread.java:1019)
08-01 20:51:36.042: E/AndroidRuntime(375): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-01 20:51:36.042: E/AndroidRuntime(375):  at android.os.Handler.<init>(Handler.java:121)
08-01 20:51:36.042: E/AndroidRuntime(375):  at android.widget.Toast.<init>(Toast.java:68)
08-01 20:51:36.042: E/AndroidRuntime(375):  at android.widget.Toast.makeText(Toast.java:231)
08-01 20:51:36.042: E/AndroidRuntime(375):  at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:161)
08-01 20:51:36.042: E/AndroidRuntime(375):  at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:1)
08-01 20:51:36.042: E/AndroidRuntime(375):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-01 20:51:36.042: E/AndroidRuntime(375):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-01 20:51:36.042: E/AndroidRuntime(375):  ... 4 more
08-01 20:51:37.142: E/WindowManager(375): Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): android.view.WindowLeaked: Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375):   at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-01 20:51:37.142: E/WindowManager(375):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-01 20:51:37.142: E/WindowManager(375):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-01 20:51:37.142: E/WindowManager(375):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.Dialog.show(Dialog.java:241)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ProgressDialog.show(ProgressDialog.java:90)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ProgressDialog.show(ProgressDialog.java:85)
08-01 20:51:37.142: E/WindowManager(375):   at com.pythagoras.machina.gr.Antallaktika$LoadData.onPreExecute(Antallaktika.java:85)
08-01 20:51:37.142: E/WindowManager(375):   at android.os.AsyncTask.execute(AsyncTask.java:391)
08-01 20:51:37.142: E/WindowManager(375):   at com.pythagoras.machina.gr.Antallaktika.onCreate(Antallaktika.java:67)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-01 20:51:37.142: E/WindowManager(375):   at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 20:51:37.142: E/WindowManager(375):   at android.os.Looper.loop(Looper.java:130)
08-01 20:51:37.142: E/WindowManager(375):   at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 20:51:37.142: E/WindowManager(375):   at java.lang.reflect.Method.invokeNative(Native Method)
08-01 20:51:37.142: E/WindowManager(375):   at java.lang.reflect.Method.invoke(Method.java:507)
08-01 20:51:37.142: E/WindowManager(375):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 20:51:37.142: E/WindowManager(375):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 20:51:37.142: E/WindowManager(375):   at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

2

您正在尝试从 UI 线程以外的线程访问 UI 功能(我猜它是 Toast)。这是不可能的。有关如何在 UI 线程上运行代码的信息,请参见此处。

于 2012-08-01T21:58:48.113 回答