错误java.lang.RuntimeException:无法启动活动

时间:2015-04-28 17:22:42

标签: android nullpointerexception onclicklistener buttonclick

我的代码中有失败,请如何解决此问题

    04-29 00:11:35.321    1849-1849/com.example.jerino.tesbaju E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jerino.tesbaju/com.example.jerino.tesbaju.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
            at android.app.ActivityThread.access$600(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.jerino.tesbaju.MainActivity.onCreate(MainActivity.java:44)
            at android.app.Activity.performCreate(Activity.java:4465)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
            at android.app.ActivityThread.access$600(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
            at dalvik.system.NativeStart.main(Native Method)
04-29 00:11:35.782    1849-1855/com.example.jerino.tesbaju I/dalvikvm﹕ threadid=3: reacting to signal 3
04-29 00:11:35.782    1849-1855/com.example.jerino.tesbaju I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
04-29 00:11:35.841    1849-1855/com.example.jerino.tesbaju I/dalvikvm﹕ threadid=3: reacting to signal 3
04-29 00:11:35.841    1849-1855/com.example.jerino.tesbaju I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'

这是我的MainActivity.java

package com.example.jerino.tesbaju;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

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


public class MainActivity extends Activity {
    EditText model,style,size,color,price;
    Button register;
    String modeltxt,styletxt,sizetxt,colortxt,pricetxt;
    List<NameValuePair> params;

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

        model = (EditText)findViewById(R.id.model);
        style = (EditText)findViewById(R.id.style);
        size = (EditText)findViewById(R.id.size);
        color = (EditText)findViewById(R.id.color);
        price = (EditText)findViewById(R.id.price);




        register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                modeltxt = model.getText().toString();
                styletxt = style.getText().toString();
                sizetxt = size.getText().toString();
                colortxt = color.getText().toString();
                pricetxt = price.getText().toString();
                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("model",modeltxt));
                params.add(new BasicNameValuePair("style",styletxt));
                params.add(new BasicNameValuePair("size",sizetxt));
                params.add(new BasicNameValuePair("color",colortxt));
                params.add(new BasicNameValuePair("price",pricetxt));
                ServerRequest sr = new ServerRequest();
                JSONObject json = sr.getJSON("http://10.0.2.2:3000/tshirts",params);
                //JSONObject json = sr.getJSON("http://192.168.56.1:8080/register",params);

                if(json != null){
                    try{
                        String jsonstr = json.getString("response");

                        Toast.makeText(getApplication(),jsonstr,Toast.LENGTH_LONG).show();

                        Log.d("Hello", jsonstr);
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }




}

这是activity_main.xml

<LinearLayout 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:orientation="vertical"

    tools:context=".MainActivity" >


    <EditText
        android:layout_width="440px"
        android:layout_height="80px"
        android:layout_gravity="center"
        android:id="@+id/model"
        android:layout_marginTop="30px"
        android:hint="example@mail.com"/>

    <EditText
        android:id="@+id/style"
        android:layout_gravity="center"
        android:layout_width="440px"
        android:layout_height="80px"
        android:inputType="textPassword"
        android:hint="******"/>
    <EditText
        android:id="@+id/size"
        android:layout_gravity="center"
        android:layout_width="440px"
        android:layout_height="80px"
        android:inputType="textPassword"
        android:hint="******"/>
    <EditText
        android:id="@+id/color"
        android:layout_gravity="center"
        android:layout_width="440px"
        android:layout_height="80px"
        android:inputType="textPassword"
        android:hint="******"/>
    <EditText
        android:id="@+id/price"
        android:layout_gravity="center"
        android:layout_width="440px"
        android:layout_height="80px"
        android:inputType="textPassword"
        android:hint="******"/>

    <Button
        android:layout_width="440px"
        android:layout_height="80px"
        android:id="@+id/registerbtn"
        android:layout_gravity="center"

        android:textColor="#ffffff"
        android:textAlignment="center"
        android:text="Register"/>




</LinearLayout>

这是我的JSON的ServerRequest.java

package com.example.jerino.tesbaju;

/**
 * Created by jerino on 28/04/15.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class ServerRequest {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";


    public ServerRequest() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {


        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }


        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;

    }
    JSONObject jobj;
    public JSONObject getJSON(String url, List<NameValuePair> params) {

        Params param = new Params(url,params);
        Request myTask = new Request();
        try{
            jobj= myTask.execute(param).get();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }catch (ExecutionException e){
            e.printStackTrace();
        }
        return jobj;
    }


    private static class Params {
        String url;
        List<NameValuePair> params;


        Params(String url, List<NameValuePair> params) {
            this.url = url;
            this.params = params;

        }
    }

    private class Request extends AsyncTask<Params, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(Params... args) {

            ServerRequest request = new ServerRequest();
            JSONObject json = request.getJSONFromUrl(args[0].url,args[0].params);

            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            super.onPostExecute(json);

        }

    }
}

最后这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jerino.tesbaju" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        <activity
            android:name=".Register"
            android:label="@string/title_activity_register" >
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

我该怎么办?谢谢先生

4 个答案:

答案 0 :(得分:0)

您忘记绑定Button寄存器,请使用:

register = (Button) findViewById(<id>);

答案 1 :(得分:0)

之前

    register.setOnClickListener(new View.OnClickListener() {

你必须添加

    register=(Button)findViewById(R.id.YourRegisterButton);

答案 2 :(得分:0)

第44行:

register.setOnClickListener(new View.OnClickListener() {

变量寄存器永远不会被初始化,这就是你有一个NullPointerException的原因。

添加:

register = (Button)findViewById(R.id.registerbtn);

答案 3 :(得分:0)

在使用之前,您必须初始化注册Button

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

    model = (EditText)findViewById(R.id.model);

    ....
    ....

    register = (Button) findViewById(R.id.registerbtn);

    register.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
           ......
           ......
        }
    });
}