好的,我有这个简单的应用程序,每次运行应用程序时都会显示来自json..unfortunatelly的数据,它会立即关闭。
我的服务器中有一个正常的api
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
mysql_connect("localhost","k4371034_android","android123");
mysql_select_db("k4371034_android");
switch($_GET['case']){
case 'sekolah':
$sql = "SELECT * FROM lokasi_checkin";
$r = mysql_query($sql);
$return_arr = array();
while($row = mysql_fetch_array($r)){
$row_array['id'] = $row['id'];
$row_array['image'] = $row['image'];
$row_array['nama'] = $row['nama'];
$row_array['long'] = $row['long'];
$row_array['lat'] = $row['lat'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
die();
break;
case 'user':
$sql = "SELECT * FROM user";
$r = mysql_query($sql);
$return_arr = array();
while($row = mysql_fetch_array($r)){
$row_array['id'] = $row['id'];
$row_array['user'] = $row['user'];
$row_array['image'] = $row['image'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
die();
break;
}
}
输出很好。
在java本身。
public class MainActivity extends AppCompatActivity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://www.lineitopkal.com/android/api.php?case=user";
private ProgressDialog pDialog;
private List<School> schoolList = new ArrayList<School>();
private ListView listView;
private CustomListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, schoolList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
//Creating volley request obj
JsonArrayRequest schoolReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
School school = new School();
school.setThumbnailUrl(obj.getString("image"));
school.setName(obj.getString("user"));
// adding school to school array
schoolList.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolReq);
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
无法看到导致问题的原因因为我的android工作室没有告诉我究竟是什么问题....它在Logcat中没有显示任何内容。
任何答案都会非常感激。谢谢你
修改
好的,事实证明问题来自我的AppController类......它给出了空指针异常。
语法
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
答案 0 :(得分:1)
使用像下面的PHP代码..
$sql = "SELECT * FROM user";
$result = $con->query($sql);
//$con database Connection
$response_arr = array();
if ($result->num_rows > 0) {
$userDetails = array();
while ($row = $result->fetch_assoc()) {
// $response["id"] = $row["id"];
$userData[] = array(
"id" => $row["id"],
"user" => $row["user"],
);
}
} else {
echo "0 results";
}
$result1['userNodes'] = $userData;
$json = json_encode($result1);
echo $json;
Volley代码使用
private void doLoginAction() {
pDialog.show();
String url_login = "http://www.lineitopkal.com/android/api.php?case=user";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String user = jo.getString("user");
Log.e("user ::",user);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Post parameter like bellow
params.put("uname", "era@gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
答案 1 :(得分:0)
问题是由于我没有在Android Manifest中正确声明应用程序名称而引起的。
我应该添加AppController作为应用程序的名称,如下所示
<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>