1. Hot New Devices! HTC One M9 | Samsung Galaxy S6 | LG G4

Json Parsen Errors


  1. glamlafp

    glamlafp New Member

    I'm developing a project with data base connection into the code.
    When i run the project and try to save inserted data, eclipse report this errors:

    Buffer Error - Error Converting Result java.lang.nullpointerException

    Json Parsen - Error Parsing Data org.jsonexception
    end of input of character 0 of

    And here it goes the following code:

    JsonParsen.java

    Code (Text):
    1. package com.example.androidhive;
    2.  
    3. import java.io.BufferedReader;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.InputStreamReader;
    7. import java.io.UnsupportedEncodingException;
    8. import java.util.List;
    9.  
    10. import org.apache.http.HttpEntity;
    11. import org.apache.http.HttpResponse;
    12. import org.apache.http.NameValuePair;
    13. import org.apache.http.client.ClientProtocolException;
    14. import org.apache.http.client.entity.UrlEncodedFormEntity;
    15. import org.apache.http.client.methods.HttpGet;
    16. import org.apache.http.client.methods.HttpPost;
    17. import org.apache.http.client.utils.URLEncodedUtils;
    18. import org.apache.http.impl.client.DefaultHttpClient;
    19. import org.json.JSONException;
    20. import org.json.JSONObject;
    21.  
    22. import android.util.Log;
    23.  
    24. public class JSONParser {
    25.  
    26.     static InputStream is = null;
    27.     static JSONObject jObj = null;
    28.     static String json = "";
    29.  
    30.     // constructor
    31.     public JSONParser() {
    32.  
    33.     }
    34.  
    35.     // function get json from url
    36.     // by making HTTP POST or GET mehtod
    37.     public JSONObject makeHttpRequest(String url, String method,
    38.             List<NameValuePair> params) {
    39.  
    40.         // Making HTTP request
    41.         try {
    42.            
    43.             // check for request method
    44.             if(method == "POST"){
    45.                 // request method is POST
    46.                 // defaultHttpClient
    47.                 DefaultHttpClient httpClient = new DefaultHttpClient();
    48.                 HttpPost httpPost = new HttpPost(url);
    49.                 httpPost.setEntity(new UrlEncodedFormEntity(params));
    50.  
    51.                 HttpResponse httpResponse = httpClient.execute(httpPost);
    52.                 HttpEntity httpEntity = httpResponse.getEntity();
    53.                 is = httpEntity.getContent();
    54.                
    55.             }else if(method == "GET"){
    56.                 // request method is GET
    57.                 DefaultHttpClient httpClient = new DefaultHttpClient();
    58.                 String paramString = URLEncodedUtils.format(params, "utf-8");
    59.                 url += "?" + paramString;
    60.                 HttpGet httpGet = new HttpGet(url);
    61.  
    62.                 HttpResponse httpResponse = httpClient.execute(httpGet);
    63.                 HttpEntity httpEntity = httpResponse.getEntity();
    64.                 is = httpEntity.getContent();
    65.             }          
    66.            
    67.  
    68.         } catch (UnsupportedEncodingException e) {
    69.             e.printStackTrace();
    70.         } catch (ClientProtocolException e) {
    71.             e.printStackTrace();
    72.         } catch (IOException e) {
    73.             e.printStackTrace();
    74.         }
    75.  
    76.         try {
    77.             BufferedReader reader = new BufferedReader(new InputStreamReader(
    78.                     is, "iso-8859-1"), 8);
    79.             StringBuilder sb = new StringBuilder();
    80.             String line = null;
    81.             while ((line = reader.readLine()) != null) {
    82.                 sb.append(line + "\n");
    83.             }
    84.             is.close();
    85.             json = sb.toString();
    86.         } catch (Exception e) {
    87.             Log.e("Buffer Error", "Error converting result " + e.toString());
    88.         }
    89.  
    90.         // try parse the string to a JSON object
    91.         try {
    92.             jObj = new JSONObject(json);
    93.         } catch (JSONException e) {
    94.             Log.e("JSON Parser", "Error parsing data " + e.toString());
    95.         }
    96.  
    97.         // return JSON String
    98.         return jObj;
    99.  
    100.     }
    101. }
    102.  

    MainActivity.java

    Code (Text):
    1. package com.example.androidhive;
    2.  
    3. import android.app.Activity;
    4. import android.content.Intent;
    5. import android.os.Bundle;
    6. import android.view.View;
    7. import android.widget.Button;
    8.  
    9.  
    10. public class MainScreenActivity extends Activity{
    11.    
    12.     Button btnViewProducts;
    13.     Button btnNewProduct;
    14.    
    15.     @Override
    16.     public void onCreate(Bundle savedInstanceState) {
    17.         super.onCreate(savedInstanceState);
    18.         setContentView(R.layout.main_screen);
    19.        
    20.         // Buttons
    21.         btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
    22.         btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
    23.        
    24.         // view products click event
    25.         btnViewProducts.setOnClickListener(new View.OnClickListener() {
    26.            
    27.             @Override
    28.             public void onClick(View view) {
    29.                 // Launching All products Activity
    30.                 Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
    31.                 startActivity(i);
    32.                
    33.             }
    34.         });
    35.        
    36.         // view products click event
    37.         btnNewProduct.setOnClickListener(new View.OnClickListener() {
    38.            
    39.             @Override
    40.             public void onClick(View view) {
    41.                 // Launching create new product activity
    42.                 Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
    43.                 startActivity(i);
    44.                
    45.             }
    46.         });
    47.     }
    48. }
    49.  
    NewProductActivity.java

    Code (Text):
    1. package com.example.androidhive;
    2.  
    3. import java.util.ArrayList;
    4. import java.util.List;
    5.  
    6. import org.apache.http.NameValuePair;
    7. import org.apache.http.message.BasicNameValuePair;
    8. import org.json.JSONException;
    9. import org.json.JSONObject;
    10.  
    11. import android.app.Activity;
    12. import android.app.ProgressDialog;
    13. import android.content.Intent;
    14. import android.os.AsyncTask;
    15. import android.os.Bundle;
    16. import android.util.Log;
    17. import android.view.View;
    18. import android.widget.Button;
    19. import android.widget.EditText;
    20.  
    21. public class NewProductActivity extends Activity {
    22.  
    23.     // Progress Dialog
    24.     private ProgressDialog pDialog;
    25.  
    26.     JSONParser jsonParser = new JSONParser();
    27.     EditText inputName;
    28.     EditText inputPrice;
    29.     EditText inputDesc;
    30.  
    31.     // url to create new product
    32.     private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php";
    33.  
    34.     // JSON Node names
    35.     private static final String TAG_SUCCESS = "success";
    36.  
    37.     @Override
    38.     public void onCreate(Bundle savedInstanceState) {
    39.         super.onCreate(savedInstanceState);
    40.         setContentView(R.layout.add_product);
    41.  
    42.         // Edit Text
    43.         inputName = (EditText) findViewById(R.id.inputName);
    44.         inputPrice = (EditText) findViewById(R.id.inputPrice);
    45.         inputDesc = (EditText) findViewById(R.id.inputDesc);
    46.  
    47.         // Create button
    48.         Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
    49.  
    50.         // button click event
    51.         btnCreateProduct.setOnClickListener(new View.OnClickListener() {
    52.  
    53.             @Override
    54.             public void onClick(View view) {
    55.                 // creating new product in background thread
    56.                 new CreateNewProduct().execute();
    57.             }
    58.         });
    59.     }
    60.  
    61.     /**
    62.      * Background Async Task to Create new product
    63.      * */
    64.     class CreateNewProduct extends AsyncTask<String, String, String> {
    65.  
    66.         /**
    67.          * Before starting background thread Show Progress Dialog
    68.          * */
    69.         @Override
    70.         protected void onPreExecute() {
    71.             super.onPreExecute();
    72.             pDialog = new ProgressDialog(NewProductActivity.this);
    73.             pDialog.setMessage("Creating Product..");
    74.             pDialog.setIndeterminate(false);
    75.             pDialog.setCancelable(true);
    76.             pDialog.show();
    77.         }
    78.  
    79.         /**
    80.          * Creating product
    81.          * */
    82.         protected String doInBackground(String... args) {
    83.             String name = inputName.getText().toString();
    84.             String price = inputPrice.getText().toString();
    85.             String description = inputDesc.getText().toString();
    86.  
    87.             // Building Parameters
    88.             List<NameValuePair> params = new ArrayList<NameValuePair>();
    89.             params.add(new BasicNameValuePair("name", name));
    90.             params.add(new BasicNameValuePair("price", price));
    91.             params.add(new BasicNameValuePair("description", description));
    92.  
    93.             // getting JSON Object
    94.             // Note that create product url accepts POST method
    95.             JSONObject json = jsonParser.makeHttpRequest(url_create_product,
    96.                     "POST", params);
    97.            
    98.             // check log cat fro response
    99.             Log.d("Create Response", json.toString());
    100.  
    101.             // check for success tag
    102.             try {
    103.                 int success = json.getInt(TAG_SUCCESS);
    104.  
    105.                 if (success == 1) {
    106.                     // successfully created product
    107.                     Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
    108.                     startActivity(i);
    109.                    
    110.                     // closing this screen
    111.                     finish();
    112.                 } else {
    113.                     // failed to create product
    114.                 }
    115.             } catch (JSONException e) {
    116.                 e.printStackTrace();
    117.             }
    118.  
    119.             return null;
    120.         }
    121.  
    122.         /**
    123.          * After completing background task Dismiss the progress dialog
    124.          * **/
    125.         protected void onPostExecute(String file_url) {
    126.             // dismiss the dialog once done
    127.             pDialog.dismiss();
    128.         }
    129.  
    130.     }
    131. }
    132.  

    Advertisement
  2. Digital Controller

    Digital Controller The Real Bass Creator Guide

    Hey there glamlafp, Let me welcome you to the site :)

    I have moved your thread into Application Development as it looks like that's where this needs to be, if you have an issue with this move, please do not hesitate to PM me :D

    Thanks for joining!

Share This Page