0

我是android开发的初学者。我编写了从 Web 服务获取数据的应用程序。首先它可以工作,但是当我在我的应用程序中编辑并添加一列数据时,它显示了一些像这样的异常 -

11-02 07:56:47.721: D/AndroidRuntime(686): Shutting down VM
11-02 07:56:47.721: W/dalvikvm(686): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
11-02 07:56:47.741: E/AndroidRuntime(686): FATAL EXCEPTION: main
11-02 07:56:47.741: E/AndroidRuntime(686): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.possampleproject/com.app.possampleproject.WelcomeActivity}: java.lang.NullPointerException
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.os.Looper.loop(Looper.java:137)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread.main(ActivityThread.java:4340)
11-02 07:56:47.741: E/AndroidRuntime(686):  at java.lang.reflect.Method.invokeNative(Native Method)
11-02 07:56:47.741: E/AndroidRuntime(686):  at java.lang.reflect.Method.invoke(Method.java:511)
11-02 07:56:47.741: E/AndroidRuntime(686):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-02 07:56:47.741: E/AndroidRuntime(686):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-02 07:56:47.741: E/AndroidRuntime(686):  at dalvik.system.NativeStart.main(Native Method)
11-02 07:56:47.741: E/AndroidRuntime(686): Caused by: java.lang.NullPointerException
11-02 07:56:47.741: E/AndroidRuntime(686):  at com.app.possampleproject.WelcomeActivity.onCreate(WelcomeActivity.java:30)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.Activity.performCreate(Activity.java:4465)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-02 07:56:47.741: E/AndroidRuntime(686):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
11-02 07:56:47.741: E/AndroidRuntime(686):  ... 11 more

第一个意图我可以运行,但是当我进入下一个意图时它会出错

MainActivity.java(我可以运行的第一个意图)

package com.app.possampleproject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    final String TAG = "boolean";
    EditText username,password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText)findViewById(R.id.username);
        final String user = new String(username.getText().toString());
        password = (EditText)findViewById(R.id.password);
        final String pass = new String(password.getText().toString());

        Button login = (Button)findViewById(R.id.button1);
        final String trueuser = new String("myusername");
        final String truepass = new String("mypassword");
        login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if(username.getText().toString().equals(trueuser) && password.getText().toString().equals(truepass)){
                    Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_SHORT).show();
                    changepage();

                }else{
                    Toast.makeText(MainActivity.this, "Wrong username or password !!", Toast.LENGTH_SHORT).show();

                }

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void changepage(){
        Intent i = new Intent(this,WelcomeActivity.class);
        startActivity(i);
    }
}

WelcomeActivity.java(第二个意图,此时我无法运行并出现错误)

package com.app.possampleproject;

import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class WelcomeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome_page);
        // set status update label.
        SharedPreferences prefs = getSharedPreferences("date", MODE_PRIVATE);
        String dateText = prefs.getString("date", "");
        TextView date = (TextView) findViewById(R.id.textupdate);
        date.setText(dateText);
        // button activity
        Button sale_but = (Button) findViewById(R.id.sale);
        Button request_but = (Button) findViewById(R.id.request);
        Button update_but = (Button) findViewById(R.id.update);
        sale_but.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                changepage();

            }
        });

        request_but.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                changepageRequest();

            }
        });

        update_but.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                setdate();

            }
        });

    }

    public void changepage() {
        Intent i = new Intent(this, SaleActivity.class);
        startActivity(i);
    }

    public void changepageRequest() {
        Intent i = new Intent(this, RequestActivity.class);
        startActivity(i);
    }

    public void setdate() {
        Calendar c = Calendar.getInstance();
        int seconds = c.get(Calendar.SECOND);
        int min = c.get(Calendar.MINUTE);
        int hour = c.get(Calendar.HOUR);
        int day = c.get(Calendar.DATE);
        int mouth = c.get(Calendar.MONTH);
        int year = c.get(Calendar.YEAR);
        SharedPreferences prefs = getSharedPreferences("date", MODE_PRIVATE);
        Editor mEditor = prefs.edit();
        mEditor.putString("date", day + "/" + mouth + "/" + year + "  " + hour
                + ":" + min + ":" + seconds);
        mEditor.commit();
        TextView date = (TextView) findViewById(R.id.textupdate);
        date.setText(day + "/" + mouth + "/" + year + "  " + hour + ":" + min
                + ":" + seconds);

    }

}

在出现错误之前,我在此意图下编辑了相同的活动

package com.app.possampleproject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class SaleActivity extends Activity {
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sale_page);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        Button cancel_but = (Button) findViewById(R.id.cancel);
        Button submit_but = (Button) findViewById(R.id.submit);

        cancel_but.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                changeToWelcome();

            }
        });

        final Button btn1 = (Button) findViewById(R.id.button1);
        // Perform action on click
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SearchData();
            }
        });

    }

    public void changeToWelcome() {
        Intent i = new Intent(this, WelcomeActivity.class);
        startActivity(i);
    }

    public void SearchData() {
        // listView1
        final ListView lisView1 = (ListView) findViewById(R.id.listView1);

        // editText1
        final EditText inputText = (EditText) findViewById(R.id.editText1);

        String url = "http://lab.richma.net/getJSONR.php";

        // Paste Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("txtKeyword", inputText.getText()
                .toString()));

        try {
            JSONArray data = new JSONArray(getJSONUrl(url, params));

            final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for (int i = 0; i < data.length(); i++) {
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("ProductID", c.getString("ProductID"));
                map.put("Size", c.getString("Size"));
                map.put("Colour", c.getString("Colour"));
                map.put("Price", c.getString("Price"));
                map.put("Quantity", c.getString("Quantity"));
                MyArrList.add(map);

            }

            // item list want to sale

            SimpleAdapter sAdap;
            sAdap = new SimpleAdapter(SaleActivity.this, MyArrList,
                    R.layout.activity_column, new String[] { "ProductID",
                            "Size", "Colour", "Price", "Quantity" }, new int[] {
                            R.id.ColProductID, R.id.ColSize, R.id.ColColour,
                            R.id.ColPrice, R.id.ColQuantity });
            lisView1.setAdapter(sAdap);

            final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this);
            // OnClick Item
            lisView1.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> myAdapter, View myView,
                        int position, long mylng) {

                    String strProductID = MyArrList.get(position)
                            .get("ProductID").toString();
                    String sSize = MyArrList.get(position).get("Size")
                            .toString();
                    String strColour = MyArrList.get(position).get("Colour")
                            .toString();
                    String strPrice = MyArrList.get(position).get("Price")
                            .toString();
                    String strQuantity = MyArrList.get(position)
                            .get("Quantity").toString();

                    viewDetail.setIcon(android.R.drawable.btn_star_big_on);
                    viewDetail.setTitle("Product Detail");
                    viewDetail.setMessage("ProductID : " + strProductID + "\n"
                            + "Size : " + sSize + "\n" 
                            + "Colour : " + strColour + "\n" 
                            + "Price : " + strPrice + "\n"
                            + "Quantity : " + strQuantity);
                    viewDetail.setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                }
                            });
                    viewDetail.setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                }
                            });
                    viewDetail.show();

                }
            });

            // sale list retrieve

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String getJSONUrl(String url, List<NameValuePair> params) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

}        

如果您想要更多信息代码,请告诉我.. 非常感谢

编辑:这是我的welcome_page.xml,感谢您的回答

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/wood">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="branch :"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="branch1"
            android:textSize="20dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/sale"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="sale" />

        <Button
            android:id="@+id/request"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="request" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="update list"
            android:textSize="20dp" /> 

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:ems="10"
            android:inputType="textMultiLine" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="update" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >    

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="Recently update" />    

            <TextView
                android:id="@+id/textupdate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="27/10/55" />

        </LinearLayout>   
    </LinearLayout>    
</LinearLayout>
4

1 回答 1

1

线条

引起:com.app.possampleproject.WelcomeActivity.onCreate(WelcomeActivity.java:30) 处的 java.lang.NullPointerException

表示根本原因在 WelcomeActivity.java 的第 30 行,您在其中使用了一个为空的变量。

可能findViewById(R.id.sale);返回 null 因为它找不到按钮。你确定它存在并且有那个ID吗?

于 2012-11-02T01:50:06.417 回答