表
我正在尝试使用下面的两个php文件检索上述数据。我想传递一个电子邮件参数并返回所有用户=电子邮件的投注。使用Advanced Rest Client进行测试时它们工作正常,因此问题不在于php。但是,当我尝试通过Android使用下面的两个java类来执行此操作时,我得到一个空指针异常(下面的logcat),并且返回的json对象为null。我不确定我的错误在哪里,我想我没有正确地将参数传递给php,这就是为什么它会产生一个空响应。
Logcat
05-31 15:10:50.227 26074-26074/com.example.albert.betterapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.albert.betterapp, PID: 26074
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.albert.betterapp/com.example.albert.betterapp.DisplayAllBets}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
at android.app.ActivityThread.access$800(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.albert.betterapp.DisplayAllBets.onCreate(DisplayAllBets.java:79)
at android.app.Activity.performCreate(Activity.java:5389)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
at android.app.ActivityThread.access$800(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Get_Bets.php
<?php
class Get_Bets {
private $db;
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$response = array();
$this->db->connect();
}
function __destruct() {
}
public function getUsersBets($email) {
$conn=mysqli_connect("****", "*****", "****","****");
$result = mysqli_query($conn,"SELECT * FROM bet WHERE user = '$email'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$response["bet"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$bet = array();
$bet["id"] = $row["id"];
$bet["stake"] = $row["stake"];
$bet["user"] = $row["user"];
$bet["returns"] = $row["returns"];
$bet["teams"] = $row["teams"];
$bet["status"] = $row["status"];
// push single gamelist into final response array
array_push($response["bet"], $bet);
}
return $response;
}
}
}
?>
Get_All_Bets.php
<?php
if (isset($_POST['email']) && $_POST['email'] != '') {
// get tag
$email = $_POST['email'];
// include db handler
require_once 'include/Get_Bets.php';
$db = new Get_Bets();
// response Array
$response = $db->getUsersBets($email);
echo json_encode($response);
}
?>
DisplayAllBets.java
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "******";
// Progress Dialog
private ProgressDialog pDialog;
private String name;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> bet;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BET = "bet";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_USER = "user";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray allgames = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
name = (getIntent().getExtras().getString("user")).toLowerCase();
Log.d("name",name);
// Hashmap for ListView
bet = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Games. 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>();
params.add(new BasicNameValuePair("email", name));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
String jsons = json.toString();
Log.d("json.tostring",jsons);
String formattedjsons = jsons.substring(jsons.indexOf('{'));
Log.d("formatted",formattedjsons);
JSONObject jObj = new JSONObject(formattedjsons);
allgames = jObj.getJSONArray(TAG_BET);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
bet.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}
/**
* 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
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
return true;
}
@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);
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
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();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
答案 0 :(得分:0)
您的Java代码执行HTTP GET请求:
var speed = 1;
setInterval(function animate() {
ctx.clearRect( 0, 0, canvas.width, canvas.height);
if (movement1 === true) {
dotHeight += speed;
if (dotHeight >= 100) movement1 = false;
// make it faster
speed += 1;
} else {
dotHeight -= speed;
if (dotHeight <= 0) movement1 = true;
// slow down
speed -= 1;
}
ctx.beginPath();
ctx.arc(canvas.width / 2, (canvas.height / 2) + dotHeight, dotSize, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}, 4);
并且您的PHP代码需要POST请求:
.table-striped tbody tr:nth-child(odd) td {
background-color: #81DAF5;
}
.table-striped tbody tr:nth-child(even) td {
background-color: #CEECF5;
}
.table-striped tbody tr.highlight td {
background-color: #F2F5A9;
}
.table-striped tbody tr:first-child td {
background-color: #FF0000;
}
您可以将Java代码更改为:
import asyncio
import logging
@asyncio.coroutine
def blocking(cmd):
while True:
logging.info("in blocking coroutine")
yield from asyncio.sleep(0.01)
print("ping")
def main():
logging.info("in main funciton")
loop = asyncio.get_event_loop()
logging.info("new loop created")
logging.info("loop running forever")
loop.run_forever()
asyncio.async(blocking("ls"))
logging.basicConfig(level = logging.INFO)
main()
或您的PHP代码:
run_forever()
我不确定这是否是唯一的问题。