应用程序在按下发送按钮时崩溃了吗?

时间:2014-07-26 18:54:41

标签: android-fragments android-asynctask

我想将数据从编辑文本发布到数据库/ php脚本,并将该数据自动显示在与编辑文本相同的片段中的列表视图中,但是当单击发送按钮时,我的应用程序崩溃。有人可以帮忙吗?

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

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

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.truevision.cypher.library.JSONParser;

public class FragmentOne extends ListFragment {

public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";

ListView listView;
EditText editText;
Button   sendBtn;

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

// url to create new post
private static final String url_post_message =  "http://example.com/myscript.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle  savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_layout_one,container, false);

    sendBtn = (Button) view.findViewById(R.id.sendBtn);
    // button click event
    sendBtn.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        // creating new post in background thread
        new Post().execute("");
        }
  });

    return view;    
}

/**
 * Background Async Task to Create new post
 * */
class Post extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Posting..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating post
     * */
    protected String doInBackground(String... args) {
        String messages = editText.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("messages", messages));

        // getting JSON Object
        // Note that create post url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_post_message,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created post

            } else {
                // failed to create post

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

}

PHP代码

<?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['messages'])) {

$messages = $_POST['messages'];

// include db connect class
require_once 'DB_Connect.php';

// connecting to db
$db = new DB_Connect();

// mysql inserting a new row
$result = mysql_query("INSERT INTO post(messages) VALUES('$messages')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Post successfully added.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

logcat的:

07-26 17:37:53.489: D/OpenGLRenderer(28074): Flushing caches (mode 0)
07-26 17:38:01.046: I/Adreno200-EGLSUB(28589): <ConfigWindowMatch:2218>: Format RGBA_8888.
07-26 17:38:01.056: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5bd46000 size:13352960 offset:11816960 fd:55
07-26 17:38:01.056: D/OpenGLRenderer(28589): Enabling debug mode 0
07-26 17:38:01.256: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5cb02000 size:21319680 offset:19783680 fd:58
07-26 17:38:02.187: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5e057000 size:11816960 offset:10280960 fd:61
07-26 17:38:14.429: I/Adreno200-EGLSUB(28589): <ConfigWindowMatch:2218>: Format RGBA_8888.
07-26 17:38:14.429: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5ed9c000 size:16711680 offset:16404480 fd:64
07-26 17:38:14.459: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5fd8c000 size:13762560 offset:13455360 fd:70
07-26 17:38:14.499: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x60aac000 size:14069760 offset:13762560 fd:73
07-26 17:38:14.650: W/dalvikvm(28589): threadid=11: thread exiting with uncaught exception (group=0x40cc31f8)
07-26 17:38:15.010: E/AndroidRuntime(28589): FATAL EXCEPTION: AsyncTask #1
07-26 17:38:15.010: E/AndroidRuntime(28589): java.lang.RuntimeException: An error occured while executing doInBackground()
07-26 17:38:15.010: E/AndroidRuntime(28589):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.lang.Thread.run(Thread.java:856)
07-26 17:38:15.010: E/AndroidRuntime(28589): Caused by: java.lang.NullPointerException
07-26 17:38:15.010: E/AndroidRuntime(28589):    at com.truevision.cypher.FragmentOne$Post.doInBackground(FragmentOne.java:85)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at com.truevision.cypher.FragmentOne$Post.doInBackground(FragmentOne.java:1)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-26 17:38:15.010: E/AndroidRuntime(28589):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-26 17:38:15.010: E/AndroidRuntime(28589):    ... 5 more
07-26 17:38:15.310: D/OpenGLRenderer(28589): Flushing caches (mode 0)
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5bd46000 size:13352960 offset:11816960
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5cb02000 size:21319680 offset:19783680
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5e057000 size:11816960 offset:10280960
07-26 17:38:15.330: D/OpenGLRenderer(28589): Flushing caches (mode 0)
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5ed9c000 size:16711680 offset:16404480
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5fd8c000 size:13762560 offset:13455360
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x60aac000 size:14069760 offset:13762560
07-26 17:38:15.841: D/OpenGLRenderer(28589): Flushing caches (mode 1)
07-26 17:38:16.591: E/WindowManager(28589): Activity com.truevision.cypher.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41689f50 that was originally added here
07-26 17:38:16.591: E/WindowManager(28589): android.view.WindowLeaked: Activity com.truevision.cypher.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41689f50 that was originally added here
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.Window$LocalWindowManager.addView(Window.java:537)
07-26 17:38:16.591: E/WindowManager(28589):     at android.app.Dialog.show(Dialog.java:278)
07-26 17:38:16.591: E/WindowManager(28589):     at com.truevision.cypher.FragmentOne$Post.onPreExecute(FragmentOne.java:78)
07-26 17:38:16.591: E/WindowManager(28589):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
07-26 17:38:16.591: E/WindowManager(28589):     at android.os.AsyncTask.execute(AsyncTask.java:511)
07-26 17:38:16.591: E/WindowManager(28589):     at com.truevision.cypher.FragmentOne$1.onClick(FragmentOne.java:56)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.View.performClick(View.java:3511)
07-26 17:38:16.591: E/WindowManager(28589):     at android.view.View$PerformClick.run(View.java:14111)
07-26 17:38:16.591: E/WindowManager(28589):     at android.os.Handler.handleCallback(Handler.java:605)
07-26 17:38:16.591: E/WindowManager(28589):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-26 17:38:16.591: E/WindowManager(28589):     at android.os.Looper.loop(Looper.java:137)
07-26 17:38:16.591: E/WindowManager(28589):     at android.app.ActivityThread.main(ActivityThread.java:4424)
07-26 17:38:16.591: E/WindowManager(28589):     at java.lang.reflect.Method.invokeNative(Native Method)
07-26 17:38:16.591: E/WindowManager(28589):     at java.lang.reflect.Method.invoke(Method.java:511)
07-26 17:38:16.591: E/WindowManager(28589):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
07-26 17:38:16.591: E/WindowManager(28589):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
07-26 17:38:16.591: E/WindowManager(28589):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

问题是NullPointerException,所以没有初始化。看起来代码似乎 在doInBackground里面你使用editText,但是没有初始化。使用view.findViewById首先初始化它。