如何解决错误转换结果java.lang.NullPointerException:lock == null

时间:2015-04-10 18:20:49

标签: php android json

我知道这个问题有几个问题,但它们都不适合我,我找不到错误,它让我疯狂。

我收到错误

  

NullPointerException:lock == null

错误

  

解析数据时出错org.json.JSONException:字符0处的输入结束。

我检查了我的JSON文件,这是有效的。我知道NullPointerException是什么,但我无法在我的代码中找到导致它的原因。

这是我的Android类:

 package com.ipmedt4.challengeweek_v2;

  import android.app.ListActivity;
  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
 import android.view.View;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
 import android.widget.ListAdapter;
 import android.widget.ListView;
 import android.widget.SimpleAdapter;
  import android.widget.TextView;

  import org.apache.http.NameValuePair;
  import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;

 public class OverzichtStudenten extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> studentList;

// url to get all products list
private static String url_all_products = "https://charlenemacdonald.com/getAlleStudenten.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_STUDENTEN = "studenten";
private static final String TAG_NAAM = "Naam";
private static final String TAG_STUDENTNUMMER = "Studentnummer";
private static final String TAG_KLAS = "Klas";
private static final String TAG_GROEP = "Groep";


// products JSONArray
JSONArray studenten = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overzicht_studenten);

    // Hashmap for ListView
    studentList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LaadAlleStudenten().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String Naam = ((TextView) view.findViewById(R.id.Naam)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    Beoordelingscherm.class);
            // sending pid to next activity
            in.putExtra(TAG_NAAM, Naam);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected 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
 * */
private class LaadAlleStudenten extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(OverzichtStudenten.this);
        pDialog.setMessage("Loading products. 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("studenten: ", json.toString());

        try {

            int success = json.getInt(TAG_SUCCESS);

            if (json != null && success == 1 ) {
                // products found
                // Getting Array of Products
                studenten = json.getJSONArray(TAG_STUDENTEN);


                // looping through All Products
                for (int i = 0; i < studenten.length(); i++) {
                    JSONObject c = studenten.getJSONObject(i);

                    // Storing each json item in variable
                    String Naam = c.getString(TAG_NAAM);
                    String Studentnummer = c.getString(TAG_STUDENTNUMMER);
                    String Klas = c.getString(TAG_KLAS);
                    String Groep = c.getString(TAG_GROEP);


                    // creating new HashMap
                    HashMap<String, String> student = new HashMap<String, String>();

                    // adding each child node to HashMap key => value;
                    student.put(TAG_NAAM, Naam);
                    student.put(TAG_STUDENTNUMMER, Studentnummer);
                    student.put(TAG_KLAS, Klas);
                    student.put(TAG_GROEP, Groep);


                    // adding HashList to ArrayList
                    studentList.add(student);
                }
            }
        } 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(
                        OverzichtStudenten.this, studentList,
                        R.layout.student_info, new String[] { TAG_NAAM,
                        TAG_STUDENTNUMMER, TAG_KLAS, TAG_GROEP},
                        new int[] { R.id.Naam, R.id.Studentnummer, R.id.Klas, R.id.Groep });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
 }

这是我的PHP文件:       

 /*
 * Following code will list all the students
 */

   $response = array();
   $response["success"] = 0;
  $response["message"] = "No students found";

   // include db connect class
   require_once __DIR__ . '/db_connect.php';

  // connecting to db
   $db = new DB_CONNECT();

  // get all products from products table
  $result = mysql_query("SELECT *FROM studenten");

  // check for empty result
  if ($result && mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["studenten"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $student = array();
    $student["Naam"] = $row["Naam"];
    $student["Studentnummer"] = $row["Studentnummer"];
    $student["Klas"] = $row["Klas"];
    $student["Groep"] = $row["Groep"];

    // push single product into final response array
    array_push($response["studenten"], $student);
 }
// success
$response["success"] = 1;

}
// Echo JSON anyway!
echo json_encode($response);
 die();
 ?>
 ?>

我的JSON Parser课程:

 package com.ipmedt4.challengeweek_v2;

  import android.util.Log;

  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpGet;
   import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.utils.URLEncodedUtils;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
   import org.json.JSONObject;

  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.UnsupportedEncodingException;
  import java.util.List;

 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) {
            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 个答案:

没有答案