I'm trying to parse below JSON which is received from server
{"status":1,"data":{"msg":"Invertory Added","inventory_id":2001}}
Using Below
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1) {
msg="Inventory Created Successfully";
} else {
msg = jObj.getString("data");
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Info")
.setMessage(msg)
.setCancelable(false)
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
if(status==1)
{
displayView(6);
}
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (JSONException e) {
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
Log says
E/msgtest﹕ unexpected JSON exception
org.json.JSONException: Value org.apache.http.conn.BasicManagedEntity#41f14cd0 of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:575)
at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:388)
at line #575 jObj = new JSONObject(json);
AsyncTask
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
File file3 = new File(selectedPath3);
File file4 = new File(selectedPath4);
File file5 = new File(selectedPath5);
String urlString="http://url/index.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
try
{
FileBody bin2 = new FileBody(file2);
FileBody bin3 = new FileBody(file3);
FileBody bin4 = new FileBody(file4);
FileBody bin5 = new FileBody(file5);
params.add(new BasicNameValuePair("section","inventory"));
params.add(new BasicNameValuePair("action","new"));
params.add(new BasicNameValuePair("apron_id",stock_number_ele.getText().toString()));
params.add(new BasicNameValuePair("nickname",nick_name_ele.getText().toString()));
params.add(new BasicNameValuePair("location",location));
params.add(new BasicNameValuePair("manufacture",manufacture));
params.add(new BasicNameValuePair("core_material",core_material_ele.getText().toString()));
params.add(new BasicNameValuePair("color",color_ele.getText().toString()));
params.add(new BasicNameValuePair("Date_purchase",dop_ele.getText().toString()));
params.add(new BasicNameValuePair("UID_no",gtin_uid_ele.getText().toString()));
params.add(new BasicNameValuePair("serial",serial_ele.getText().toString()));
params.add(new BasicNameValuePair("Batch",batch_lot_ele.getText().toString()));
params.add(new BasicNameValuePair("Expiration",ed_ele.getText().toString()));
params.add(new BasicNameValuePair("garment_type",description_ele.getText().toString()));
params.add(new BasicNameValuePair("QTY",county_ele.getText().toString()));
params.add(new BasicNameValuePair("user_id",SignInActivity.user_id));*/
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
FileBody bin3 = new FileBody(file3);
FileBody bin4 = new FileBody(file4);
FileBody bin5 = new FileBody(file5);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("section", new StringBody("inventory"));
reqEntity.addPart("action", new StringBody("new"));
reqEntity.addPart("apron_id", new StringBody(stock_number_ele.getText().toString()));
reqEntity.addPart("nickname", new StringBody(nick_name_ele.getText().toString()));
reqEntity.addPart("location", new StringBody(location+""));
reqEntity.addPart("manufacture", new StringBody(manufacture+""));
reqEntity.addPart("core_material", new StringBody(core_material_ele.getText().toString()));
reqEntity.addPart("color", new StringBody(color_ele.getText().toString()));
reqEntity.addPart("Date_purchase", new StringBody(dop_ele.getText().toString()));
reqEntity.addPart("UID_no", new StringBody(gtin_uid_ele.getText().toString()));
reqEntity.addPart("serial", new StringBody(serial_ele.getText().toString()));
reqEntity.addPart("Batch", new StringBody(batch_lot_ele.getText().toString()));
reqEntity.addPart("Expiration", new StringBody(ed_ele.getText().toString()));
reqEntity.addPart("garment_type", new StringBody(description_ele.getText().toString()));
reqEntity.addPart("QTY", new StringBody(county_ele.getText().toString()));
reqEntity.addPart("user_id", new StringBody(SignInActivity.user_id));
if(selectedPath1!="NONE")
reqEntity.addPart("image1", bin1);
if(selectedPath2!="NONE") {
Log.d("Image2","Image2");
reqEntity.addPart("image2", bin2);
}
if(selectedPath3!="NONE") {
Log.d("Image3","Image2");
reqEntity.addPart("image3", bin3);
}
if(selectedPath4!="NONE") {
Log.d("Image4","Image2");
reqEntity.addPart("image4", bin4);
}
if(selectedPath5!="NONE") {
Log.d("Image5","Image2");
reqEntity.addPart("image5", bin5);
}
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
}
}
catch (Exception ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return resEntity.toString();
}
#SuppressWarnings("deprecation")
//#Override
protected void onPostExecute(String json) {
String msg="";
JSONArray jArray=null;
if (pDialog.isShowing()) {
pDialog.dismiss();
}
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
msg = jObj.getString("data"); // get the name from data.
if (status == 1) {
msg="Inventory Created Successfully";
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Info")
.setMessage(msg)
.setCancelable(false)
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(status==1)
{
displayView(6);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
Please suggest your views . Thanks in advance.
your are correctly using EntityUtils.toString to read the content of the entity and as a String, but you are returning the wrong object in doInBackground. Instead of returning resEntity.toString();, you have to return response_str.
I think I know why this code is failing.
in your code you have :
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1)
{
msg = "Inventory Created Successfully";
}
else
{
msg = jObj.getString("data");
}
...
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
You said that you were receiving JSON messages like this (I added the types of the fields):
// "Main" Object
{
"status": 1, // Integer
"data": // Object
{
"msg" : "Invertory Added", // String
"inventory_id" : 2001 // Integer
}
}
So in your code when you try this msg = jObj.getString("data"); you ask a String BUT in your JSON message "data" is of the type Object which is why you get this Error.
So instead you should do this :
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1)
{
msg = "Inventory Created Successfully";
}
else
{
// Here is the change
// you should also change the type of msg to JSONObject
// and probably the name of the variable for a better understanding
msg = jObj.getObject("data");
}
// And of course handle this object accordingly
// Example : String message = msg.getString("msg");
...
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
If I am guessing right you wanted to retrieve the "msg" field inside the "data" Object. You can simply get it like so :
String message = jObj.getObject("data").getString("msg");
Hope this helps,
Cheers.
Related
I am trying to connect my Android Application with mySQL. I am getting error in LogCat.
You can find my complete code here https://github.com/rraj56801/php-connection
I am concerning only on getting all product here.
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.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("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
JSONParser code here:
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);
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
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(new BasicHttpParams());
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://127.0.0.1");
try{
// Execute the request in the client
HttpResponse httpResponse = httpclient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
}catch(Exception e){
Log.d("Error",e.toString());
}
}
} 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;
}
LogCat here:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'int org.json.JSONObject.getInt(java.lang.String)' on a null
object reference
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:134)
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
you are having problem in this line.
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
your json object is not getting value hence remains null. and letter you are trying to access a method of null object so the error occurs. check you url
or else check value before using
if(json != null)
{
try
{
int success = json.getInt(TAG_SUCCESS);
...
...
...
}
}
My client type is android and the language is Java.
This class connects to the server and gets the output stream to the connected server.
class ConnectToServer extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try {
socket = new Socket(ip,port);
output = new DataOutputStream(socket.getOutputStream());
Log.d(TAG, "Connected To Server!");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class SendToServer extends AsyncTask<Void, Void, Void>
{
//Our Json object
JSONObject obj;// = new JSONObject();
//this class is called when the login button is pressed, it sends the username and password as arguments
public SendToServer(String username, String password)
{
//instantiate the new object
obj = new JSONObject();
try {
//create the first field Type
obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request
obj.put("username", username); //our server will get username
obj.put("password",password); //our server will get password
} catch (JSONException e) {
e.printStackTrace(); //if we get problems let the developer know
}
}
#Override
protected Void doInBackground(Void... params)
{
String jsonText = obj.toString(); //convert our json object into a string
byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array
try {
output.writeInt(b.length); // write length of the message
output.write(b); // write the message
output.flush(); //flush - empties the pipe
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
The purpose of this code is to send the server the users credentials.
In this C# Server
private void serverClient()
{
while(true)
{
int len = ns.ReadByte(); //read how much data
if (len == 0) //if this == 0 this means client has quit the program
break; //break out of loop and remove client from array list
if (len > 0) //we have a message
{
//read mess
byte[] message = new byte[len]; //create byte array
ns.Read(message, 0, message.Length); //read into the message byte array
string text = Encoding.ASCII.GetString(message, 0, len);
string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got.
Console.WriteLine(text1);
}
}
removeClients();
}
So the Android client will send the credentials, but when the SendToServer class is called, the client disconnects from the server.
How can I send a Json string to my C# server so it can then read the string and serialize it into an object, depending on the fields.
private void updateDataToServer() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_update);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
/*
* Toast.makeText(getBaseContext(), "Update Successfully",
* Toast.LENGTH_SHORT).show();
*/
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
class PostDataToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
* pDialog = new ProgressDialog(MainActivity.this);
* pDialog.setMessage("Please wait..."); pDialog.show();
*/
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_create_product);
try {
name = edt_name.getText().toString();
score = edt_score.getText().toString();
quocgia = edt_quocgia.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
#Override
protected void onPostExecute(String s) {
/*
* if (pDialog.isShowing()) { pDialog.dismiss();
* Toast.makeText(getApplication(), "Complete",
* Toast.LENGTH_LONG).show(); }
*/
}
}
Hope it helps you
You're reading lines but you aren't writing lines. Add a line terminator to the message being sent, or use println() instead of write().
I have a problem with some information downloaded from a DDBB. I recieve all the information, but I can't store it on my arrays because the onPostExecute() method doesn't starts. I put my code:
RequestRocodromo.java, is the class for making the request and recieve the information, on "results" variable I have all the information, but I can't storage it on the arrays of onPostExecute():
#Override
protected JSONObject doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_url);
String results = "NO OK";
try
{
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("mac", _mac ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getAllHeaders();
response.getEntity();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(response.getEntity());
}
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject jsonResponse)
{
super.onPostExecute(jsonResponse);
List<String> values = new ArrayList<String>();
ArrayList<String> rocodromoId = new ArrayList<String>();
ArrayList<String> rocodromoArray = new ArrayList<String>();
ArrayList<String> ciudadArray = new ArrayList<String>();
ArrayList<String> comentarioArray = new ArrayList<String>();
//Procesamos los resultados
try
{
if(jsonResponse != null)
{
JSONArray jsonMainNode =jsonResponse.optJSONArray("edificios");
int lengthJsonArr =jsonMainNode.length();
for(int i=0; i<lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
rocodromoId.add(jsonChildNode.optString("id"));
rocodromoArray.add(jsonChildNode.optString("nombre"));
ciudadArray.add(jsonChildNode.optString("ciudad"));
comentarioArray.add(jsonChildNode.optString("comentario"));
values.add(jsonChildNode.optString("nombre"));
}
}
String result[] = values.toArray(new String[values.size()]);
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception e)
{
String result = "null";
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
}
Rocodromo.java, here is where I start the execute method:
RequestRocodromo re = new RequestRocodromo(ctx, finalURL + "request=1");
re.execute("");
Rocodromo.java, here is my broadcast, when I try to obtain the arraylist information I recieve a nullException, because my arraylist are null because it never starts the onPostExecute() method.
public class ReceptorBroadcast extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(RequestRocodromo.ACTION_REQUEST_ROCODROMO.equals(intent.getAction()))
{
idRocodromo = intent.getStringArrayListExtra("id_rocodromo");
Toast.makeText(getApplicationContext(), idRocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
rocodromo = intent.getStringArrayListExtra("rocodromoArray");
Toast.makeText(getApplicationContext(), rocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
ciudad = intent.getStringArrayListExtra("ciudadArray");
Toast.makeText(getApplicationContext(), ciudad.get(0).toString(), Toast.LENGTH_LONG).show();
comentario = intent.getStringArrayListExtra("comentarioArray");
Toast.makeText(getApplicationContext(), comentario.get(0).toString(), Toast.LENGTH_LONG).show();
}
}
}
Can someone help my with that? Thanks! :)
Change on doInBackGround return null to:
try {
return new JSONObject(reusults);
} catch (Throwable t) {
return null;
}
Change you broadcast receiver call in your doInBackground().. as
runOnUiThread(new Runnable() {
#Override
public void run() {
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
});
and check null result in onPostExecute as..
if(null!=jsonResponse) // avoids null pointer;
my app which is supposed to transfer user input data to my SQL database. I am supposed to fill in all fields, then click save so that data gets updated in my sql databse. After cleaning up a lot of errors, i am finally stuck on 1 error that i cant resolve. any help provided would be extremely appreciated.Please advice what changes i can make to get rid of the error. The error is
08-04 05:47:48.799: E/JSON Parser(1506): Error parsing data [End of input at character 0 of ]
My codes below:
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputDriver;
EditText inputLicence;
EditText inputOfficer;
EditText inputSpeed;
EditText FineAppl;
EditText inputCategory;
TextView registerFine;
// url to create new fine
private static String url_create_fine = "http://192.168.1.1/android_api/create.php";
// JSON Node names/
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speed = (EditText) findViewById(R.id.editText3);
Fine = (TextView)findViewById(R.id.editText4);
btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
inputDriver = (EditText) findViewById(R.id.editText1);
inputLicence = (EditText) findViewById(R.id.editText2);
inputOfficer = (EditText) findViewById(R.id.editText5);
inputSpeed = (EditText) findViewById(R.id.editText3);
FineAppl = (EditText) findViewById(R.id.editText4);
inputCategory = (EditText) findViewById(R.id.editText6);
registerFine = (TextView) findViewById(R.id.fineregistered);
// Create button
Button btnRegisterfine = (Button) findViewById(R.id.savefine);
// button click event
btnRegisterfine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewFine().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewFine extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FineCalc.this);
pDialog.setMessage("Registering Fine..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String driver = inputDriver.getText().toString();
String licencenum = inputLicence.getText().toString();
String officer = inputOfficer.getText().toString();
String speed = inputSpeed.getText().toString();
String fine= FineAppl.getText().toString();
String category = inputCategory.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("driver", driver));
params.add(new BasicNameValuePair("licencenum", licencenum));
params.add(new BasicNameValuePair("officer", officer));
params.add(new BasicNameValuePair("speed", speed));
params.add(new BasicNameValuePair("fine", fine));
params.add(new BasicNameValuePair("category", category));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_fine, "POST", params);
// check log cat from response
//Log.d("Create Response", json.toString());
// check for success tag
try {
//if (json.getString(TAG_SUCCESS) != null) {
if(json != null && !(json).isNull(TAG_SUCCESS)){
registerFine.setText("");
String success = json.getString(TAG_SUCCESS);
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
if(Integer.parseInt(success) == 1){
// successfully created product
//Intent i = new Intent(getApplicationContext(), UserLogin.class);
//startActivity(i);
registerFine.setText("Successful");
// closing this screen
finish();
} else {
} // failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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, HTTP.UTF_8), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(
// is, HTTP.UTF_8), 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());
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
// return JSON String
return jObj;
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
And My php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){
$driver = $_POST['driver'];
$licencenum = $_POST['licencenum'];
$officer = $_POST['officer'];
$speed = $_POST['speed'];
$fine = $_POST['fine'];
$category = $_POST['category'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES ('$driver','$licencenum','$officer','$speed','$fine', '$category')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Speed Ticket Successfully Registered.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
HttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
pass the string into json array and get the response value
JSONArray jsArray = new JSONArray(responseBody);
JSONObject js = jsArray.getJSONObject(0);
String returnvalmsg = js.getString("message");
String returnvalsucc = js.getString("success");
Hint: pass success as "0" not 0
I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e){
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e){
Log.e("Fail 2", e.toString());
}
try {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));