简体   繁体   English

Android Volley显示JSON数据

[英]Android Volley Display JSON Data

Okay I have this simple app to display data from json..unfortunatelly everytime I run the app, it closed immediately. 好的,我有这个简单的应用程序,每次运行该应用程序时,它都会显示json..unfortunatelly的数据,它会立即关闭。

I have a working fine api in my server 我的服务器上有正常工作的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;
  } 
}

It output just fine. 它输出就好了。

In java itself. 在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;
  }
}

Cannot see what cause the problem cuz my android studio didn't tell what exactly the problem is....it showed nothing in Logcat. 无法看到导致问题的原因,原因是我的Android Studio并未确切说明问题是什么...。它在Logcat中什么也没显示。

Any answer will be really appreciated. 任何答案将不胜感激。 Thank u 感谢你

EDIT 编辑

Okay it turns out that the problem comes from my AppController class...which giving null pointer exception. 好的,事实证明,问题出在我的AppController类上,它给出了空指针异常。

The syntax 语法

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);
    }
  }
}
  1. Use php code like bellow.. 使用类似下面的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; 
  2. Volley code use like 凌空代码使用像

      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); } 

The problem was caused because I didn't properly declared the name of application in Android Manifest. 造成此问题的原因是我没有在Android Manifest中正确声明应用程序的名称。

I supposed to add AppController as the name of the application like below 我应该添加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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM