【问题标题】:Error when launch android apps read data SQL from php file启动 android 应用程序从 php 文件读取数据 SQL 时出错
【发布时间】:2016-06-08 10:23:04
【问题描述】:

我有一个程序可以使用 php 文件读取 SQL Server 中的外部数据。我做了两个菜单项,例如新闻从 MySQL 获取数据,禁止列表从 SQL Server 获取数据。新闻菜单和禁止列表使用相同的代码。新闻菜单运行完美,没有任何错误,但是当我运行禁止列表时,程序会像这样自动关闭我http://prntscr.com/bdss23

我在logcat上看到有这样的错误

06-08 05:54:58.335    1276-1276/net.dragon_dev.www.dzoneconnect E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts$1.run(ListBannedActivity.java:189)
        at android.app.Activity.runOnUiThread(Activity.java:4673)
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts.onPostExecute(ListBannedActivity.java:178)
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts.onPostExecute(ListBannedActivity.java:106)
        at android.os.AsyncTask.finish(AsyncTask.java:631)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
06-08 06:07:57.667    1309-1309/net.dragon_dev.www.dzoneconnect E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts$1.run(ListBannedActivity.java:189)
        at android.app.Activity.runOnUiThread(Activity.java:4673)
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts.onPostExecute(ListBannedActivity.java:178)
        at net.dragon_dev.www.dzoneconnect.ListBannedActivity$LoadAllProducts.onPostExecute(ListBannedActivity.java:106)
        at android.os.AsyncTask.finish(AsyncTask.java:631)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

logcat 中的第一个错误 (ListBannedActivity.java:189)

getListView().setAdapter(adapter);

logcat 中的第二个错误 (ListBannedActivity.java:178)

runOnUiThread(new Runnable() {

logcat 中的第三个错误 (ListBannedActivity.java:106)

 class LoadAllProducts extends AsyncTask<String, String, String> {

我在 ListBannedActivity.java 中的完整代码

public class ListBannedActivity extends AppCompatActivity {

Toolbar toolbar;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();

private ListView listView;

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://192.168.1.111/top_kill.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "topkill";
private static final String TAG_NAME = "Name";
private static final String TAG_KILL = "Kill";
private static final String TAG_DEATH = "Death";

// products JSONArray
JSONArray products = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_topkill);
    // ListView listView = (ListView) findViewById(android.R.id.list);
    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    TypedValue typedValueColorPrimaryDark = new TypedValue();
    ListBannedActivity.this.getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValueColorPrimaryDark, true);
    final int colorPrimaryDark = typedValueColorPrimaryDark.data;
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setStatusBarColor(colorPrimaryDark);
    }
}

// Get listview
protected ListView getListView(){
    if (listView == null) {
        listView = (ListView) findViewById(R.id.lista);
    }
    return listView;
}

// Response from Edit Product Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ListBannedActivity.this);
        pDialog.setMessage("Loading. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String name = c.getString(TAG_NAME);
                    String kill = c.getString(TAG_KILL);
                    String death = c.getString(TAG_DEATH);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_NAME, name);
                    map.put(TAG_KILL, kill);
                    map.put(TAG_DEATH, death);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                Toast.makeText(getApplicationContext(), "Doesn't have banned players now", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        ListBannedActivity.this, productsList,
                        R.layout.list_topkill, new String[]{
                        TAG_NAME, TAG_KILL, TAG_DEATH},
                        new int[]{R.id.name, R.id.timestamp, R.id.timestamp1});
                // updating listview
                getListView().setAdapter(adapter);
            }
        });
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    getMenuInflater().inflate(R.menu.menu_news, menu);
    return super.onCreateOptionsMenu(menu);
}

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

我的php代码是这样的

<?php
/* All database connection variables */
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "RF_World"); // database name
define('DB_SERVER', "127.0.0.1"); // db server

class DB_CONNECT {
// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/** Function to connect with database **/
function connect() {

    // Connecting to mssql database
    $con = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mssql_error());

    // Selecing database
    $db = mssql_select_db(DB_DATABASE) or die(mssql_error()) or die(mssql_error());

    // returing connection cursor
    return $con;
}

/** Function to close db connection **/
function close() {
    // closing db connection
    mssql_close();
}
}
/*
* Following code will list all the products
*/

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

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

// get all news update dzc
$result = mssql_query("SELECT TOP 1 Name, [Kill], Death FROM tbl_pvporderview 
JOIN tbl_base
ON tbl_pvporderview.serial = tbl_base.Serial
ORDER BY [Kill] DESC;") or die(mssql_error());

 // check for empty result
 if (mssql_num_rows($result) > 0) {
 // looping through all results
 // products node
 $response["topkill"] = array();

 while ($row = mssql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["Name"] = $row["Name"];
    $product["Kill"] = ceil($row["[Kill]"]);
    $product["Death"] = ceil($row["Death"]);

    // push single product into final response array
    array_push($response["topkill"], $product);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No News DZoneConnect Now";

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

谁能帮我解决我的问题?

谢谢

【问题讨论】:

  • onPostExecute 在 ui 线程上运行,您不需要执行 runOnUiThread(new Runnable() { 部分。还有stackoverflow.com/questions/218384/…——你的listView仍然是null,可能是因为R.layout.activity_topkill中没有id为R.id.lista的视图
  • 是的,你说得对,没有 R.id.lista,我改变了布局,只得到 1 个像这样的错误prntscr.com/bdtduq

标签: java php android sql-server web-services


【解决方案1】:

在 onCreate() 方法中添加这一行:

    listView = (ListView) findViewById(R.id.lista);

无需编写getListView()等任何方法。 由于您没有显示任何进展,因此请在您的 AsyncTask 中进行一项更改:

class LoadAllProducts extends AsyncTask<String, Void, String> // do this

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2010-09-30
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多