简体   繁体   中英

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.

I have a working fine api in my server

<?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.

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.

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.

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..

      $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.

I supposed to add AppController as the name of the application like below

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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