我的Android应用程序在开始时崩溃

时间:2014-05-19 19:56:33

标签: android crash

我启动了一个应用程序,它通过php脚本从数据库中检索数据,将它们显示为列表。

我的问题是应用程序在启动时崩溃了。我不了解logcat,因为我从java开始。

这是logcat:

05-19 15:28:33.650: W/dalvikvm(1018): threadid=1: thread exiting with uncaught exception (group=0xb3a3aba8)
05-19 15:28:33.680: E/AndroidRuntime(1018): FATAL EXCEPTION: main
05-19 15:28:33.680: E/AndroidRuntime(1018): Process: gsb.listegsb, PID: 1018
05-19 15:28:33.680: E/AndroidRuntime(1018): java.lang.RuntimeException: Unable to start activity ComponentInfo{gsb.listegsb/gsb.listegsb.MainActivity}: android.os.NetworkOnMainThreadException
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.os.Looper.loop(Looper.java:136)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.lang.reflect.Method.invokeNative(Native Method)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.lang.reflect.Method.invoke(Method.java:515)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at dalvik.system.NativeStart.main(Native Method)
05-19 15:28:33.680: E/AndroidRuntime(1018): Caused by: android.os.NetworkOnMainThreadException
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.net.Socket.connect(Socket.java:843)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:131)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.Connection.connect(Connection.java:101)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at java.net.URL.openStream(URL.java:470)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at model.Passerelle.getLesVis(Passerelle.java:31)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at gsb.listegsb.MainActivity.onCreate(MainActivity.java:34)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.Activity.performCreate(Activity.java:5231)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-19 15:28:33.680: E/AndroidRuntime(1018):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-19 15:28:33.680: E/AndroidRuntime(1018):     ... 11 more

和Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="gsb.listegsb"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="gsb.listegsb.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity:

package gsb.listegsb;

import java.util.List;

import model.Passerelle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Build;

public class MainActivity extends ActionBarActivity {
    List<String> lesVis;
    ListView  lvListe;

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        lesVis = Passerelle.getLesVis();

        lvListe = (ListView)findViewById(R.id.listViewDep);
        // Création de l'adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lesVis);
        lvListe.setAdapter(adapter);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

不同的课程:

package model;

public class Visiteur {
    private String matricule;

    public Visiteur(String matricule)
    {
        this.matricule = matricule;
    }

    public String getMatricule()
    {
        return matricule;
    }
}

Rapport:

package model;

public class Rapport {
    private String matricule;
    private int numRap;
    private int numPract;
    private String bilan;
    private String motif;

    public Rapport(String matricule, int numRap, int numPract, String bilan, String motif)
    {
        this.matricule = matricule;
        this.numRap = numRap;
        this.numPract = numPract;
        this.bilan = bilan;
        this.motif = motif;
    }

    public String getMatricule()
    {
        return matricule;       
    }

    public int getNumRap()
    {
        return numRap;
    }

    public int getNumPract()
    {
        return numPract;
    }

    public String getBilan()
    {
        return bilan;
    }

    public String getMotif()
    {
        return motif;
    }

}

Passerelle:

package model;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Passerelle {
    private static String _urlVis = "http://10.0.2.2/matricule.php";

    public static List<String> getLesVis() {
        List<String> lesVis = new ArrayList<String>();
        try {
            URL myURL = new URL(_urlVis);
            Document doc;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

            doc = db.parse(myURL.openStream());

            Element racine = doc.getDocumentElement();

        NodeList listeVis = racine.getElementsByTagName("visiteur");

        for (int i = 0; i < listeVis.getLength(); i++) {
            Node visiteur = listeVis.item(i);
            NodeList lesProprietes = visiteur.getChildNodes();
        // recherche du nom
            for (int j = 0; j < lesProprietes.getLength(); j++) {
                if (lesProprietes.item(j).getNodeName().equals("matricule")) {
                 lesVis.add(lesProprietes.item(j).getTextContent().trim());
                 break;
                    }
              }
           }
        } 
    catch (SAXException ex) {
        Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE, null, ex);
        }
     catch (ParserConfigurationException ex) {
      Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE, null, ex);
                }
     catch (IOException ex) {
        Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE, null, ex);
        }
    return lesVis;
    }
}

我希望有人可以帮助我。

提前致谢。

1 个答案:

答案 0 :(得分:1)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行代码:

你的Passerelle应该延长

android AsyncTask

  

样品

private abstract class Passerelle extends AsyncTask<String, Void, String> implements OnTaskCompleted
{
List<String> lesVis = new ArrayList<String>();

@Override
protected String doInBackground(String... urls)
{
    try
    {
        URL myURL = new URL(_urlVis);
        Document doc;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        doc = db.parse(myURL.openStream());

        Element racine = doc.getDocumentElement();

        NodeList listeVis = racine.getElementsByTagName("visiteur");

        for (int i = 0; i < listeVis.getLength(); i++)
        {
            Node visiteur = listeVis.item(i);
            NodeList lesProprietes = visiteur.getChildNodes();
            // recherche du nom
            for (int j = 0; j < lesProprietes.getLength(); j++)
            {
                if (lesProprietes.item(j).getNodeName().equals("matricule"))
                {
                    lesVis.add(lesProprietes.item(j).getTextContent()
                            .trim());
                    break;
                }
            }
        }
    } catch (SAXException ex)
    {
        Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE,
                null, ex);
    } catch (ParserConfigurationException ex)
    {
        Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE,
                null, ex);
    } catch (IOException ex)
    {
        Logger.getLogger(Passerelle.class.getName()).log(Level.SEVERE,
                null, ex);
    }
    return "";
}

public abstract void onResponseReceived(Lis<String> strings);

@Override
protected void onPostExecute(String result)
{
    onResponseReceived(lesVis);
}

}

  

OnTaskCompleted

public interface OnTaskCompleted
{
public void onResponseReceived(List<String> result);
}
  

代替您的实际通话

lesVis = Passerelle.getLesVis();

这样做

Passerelle service = new Passerelle()
    {
        @Override
        public void onResponseReceived(List<String> result)
        {
            lesVis = result;
        }
    };
    service.execute(urlVis);