启动android应用程序时发生错误从php文件中读取数据SQL
问题描述:
我有一个程序使用php文件读取SQL Server中的外部数据。我做了两个菜单项,比如新闻从MySQL获取数据,禁止列表从SQL Server获取数据。新闻菜单和被禁止列表使用相同的代码。新闻菜单运行完全没有任何错误,但是当我运行被禁之列,程序自动关闭这样我http://prntscr.com/bdss23启动android应用程序时发生错误从php文件中读取数据SQL
和我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);
}
?>
有人能帮助我解决我的问题?
感谢的
答
加入这一行onCreate()方法:
listView = (ListView) findViewById(R.id.lista);
无需作出任何方法如getListView()。 既然你没有显示任何进展使你的AsyncTask
一个变化:
class LoadAllProducts extends AsyncTask<String, Void, String> // do this
+0
得到同样的错误,我已经按照你的指示 –
'onPostExecute'运行在UI线程上,你不需要做'runOnUiThread(新的Runnable(){'一部分。也是http://*.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix-it - 你的'listView'仍然是'null',可能是因为没有没有这样的在'R.layout.activity_topkill'中使用ID'R.id.lista'查看 – zapl
是的,你没有R.id.lista,我改变了布局,只有1个错误,像这样http://prntscr.com/ bdtduq –