我正在制作一个连接到外部mysql数据库的android应用程序,并成功地从数据库中获取图像。当我点击单个项目时,它将用更新按钮打开另一个具有选定项目数据的活动。我成功地检索了数据。但当我点击更新按钮时,它显示以下错误
分析数据org.json.JSONException时出错:java.lang.String类型的值UPDATE无法转换为JSONObject
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="16dp"
android:text="TextView" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="17dp"
android:layout_toRightOf="@+id/textView1"
android:src="@drawable/abc_ab_bottom_solid_dark_holo" />
</RelativeLayout>
Single_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="22dp"
android:text="TextView" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_marginLeft="18dp"
android:layout_toRightOf="@+id/textView1"
android:src="@drawable/abc_ab_bottom_solid_dark_holo" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="24dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="27dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_marginTop="68dp"
android:layout_toRightOf="@+id/textView1"
android:text="Button" />
</RelativeLayout>
Mainactivity.java code
public class MainActivity extends ActionBarActivity {
private ProgressDialog pDailog;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>>myarralist;
JSONArray countrys=null;
ListView listView;
ListViewAdapter adapter;
JSONfunctions jfunction=new JSONfunctions();
private static String url_all_products="http://192.168.1.7/abc/get_all_products.php";
static String TAG_SUCCESS="success";
static String TAG_PRODUCTS="image";
static String TAG_IMGID="ImageID";
static String TAG_NAME="ImageDesc";
static String TAG_DESC="Desc";
static String TAG_FLAG="ImagePath";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DOWNLoaddata().execute();
}
private class DOWNLoaddata extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDailog=new ProgressDialog(MainActivity.this);
pDailog.setTitle("Android JSON Parse Tutorial");
pDailog.setMessage("Loading...");
pDailog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
myarralist=new ArrayList<HashMap<String,String>>();
List<NameValuePair>params=new ArrayList<NameValuePair>();
jsonObject=jfunction.makeHttpRequest(url_all_products, "GET", params);
Log.d("All countrys", jsonObject.toString());
try {
jsonArray=jsonObject.getJSONArray("image");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String>map=new HashMap<String, String>();
jsonObject=jsonArray.getJSONObject(i);
map.put("ImageID", jsonObject.getString("ImageID"));
map.put("ImageDesc", jsonObject.getString("ImageDesc"));
map.put("Desc", jsonObject.getString("Desc"));
map.put("ImagePath", jsonObject.getString("ImagePath"));
myarralist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
listView=(ListView)findViewById(R.id.listView1);
adapter=new ListViewAdapter(MainActivity.this, myarralist);
listView.setAdapter(adapter);
pDailog.dismiss();
}
}
}
Singleactivity.java code
public class Singleitemview extends Activity {
String id;
String country;
String desc;
String flag;
ProgressDialog pdialog;
Bitmap bmimg=null;
Button btnupdate;
EditText edcou,eddesc;
TextView txtid;
ImageView imf;
JSONfunctions jfun=new JSONfunctions();
private static String url_update_product="http://192.168.1.7/abc/update_product.php";
//private static String url_product_detials="http://192.168.1.5/android_connect/get_product_details.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_PRODUCTS="image";
private static final String TAG_COUNT="ImageDesc";
private static final String TAG_DESC="DESC";
private static final String TAG_IMAGEPATH = "ImagePath";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_item);
new Loaddata().execute();
Intent i=getIntent();
id=i.getStringExtra("ImageID");
country=i.getStringExtra("ImageDesc");
desc=i.getStringExtra("Desc");
flag=i.getStringExtra("ImagePath");
edcou=(EditText)findViewById(R.id.editText1);
eddesc=(EditText)findViewById(R.id.editText2);
btnupdate=(Button)findViewById(R.id.button1);
btnupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new save().execute();
}
});
}
class save extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog=new ProgressDialog(Singleitemview.this);
pdialog.setMessage("Loading..");
pdialog.show();
}
@Override
protected String doInBackground(String... args) {
country=edcou.getText().toString();
desc=eddesc.getText().toString();
//String img=imf.getImageMatrix().toString();
List<NameValuePair>params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ImageID", id));
params.add(new BasicNameValuePair("ImageDesc", country));
params.add(new BasicNameValuePair("Desc", desc));
params.add(new BasicNameValuePair("ImagePath", flag));
JSONObject json=jfun.makeHttpRequest(url_update_product, "POST", params);
Log.d("single countrys", json.toString());
try {
int success=json.getInt(TAG_SUCCESS);
if (success==1) {
//country=json.getString("ImageDesc");
//des=json.getString("Desc");
//edcou.setText(country);
//eddesc.setText(des);
//Intent i=new Intent(getApplicationContext(),MainActivity.class);
//startActivity(i);
//finish();
Intent i=getIntent();
setResult(100,i);
finish();
}else {
// Toast.makeText(getApplicationContext(), "sorry", Toast.LENGTH_LONG).show();
System.out.println("Not updated!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
pdialog.dismiss();
}
}
public class Loaddata extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog=new ProgressDialog(Singleitemview.this);
pdialog.setMessage("Loading..");
pdialog.show();
}
@Override
protected String doInBackground(String... params) {
try {
Intent i=getIntent();
id=i.getStringExtra("ImageID");
country=i.getStringExtra("ImageDesc");
desc=i.getStringExtra("Desc");
flag=i.getStringExtra("ImagePath");
URL url=new URL(flag);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is=conn.getInputStream();
bmimg=BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
TextView idd=(TextView)findViewById(R.id.textView1);
EditText countryy=(EditText)findViewById(R.id.editText1);
EditText desdc=(EditText)findViewById(R.id.editText2);
ImageView imgb=(ImageView)findViewById(R.id.imageView1);
idd.setText(id);
countryy.setText(country);
desdc.setText(desc);
imgb.setImageBitmap(bmimg);
pdialog.dismiss();
}
}
}
JSONFunctions
public class JSONfunctions {
static InputStream is=null;
static JSONObject jObj=null;
static String json="";
public JSONfunctions() {
// TODO Auto-generated constructor stub
}
public JSONObject makeHttpRequest(String url,String method,List<NameValuePair>params)
{
try {
if (method=="POST") {
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) {
if (line.startsWith("{")) {
}
sb.append(line + "n");
}
is.close();
json=sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
try {
jObj=new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
return jObj;
}
public static JSONObject getjObj() {
return jObj;
}
public static void setjObj(JSONObject jObj) {
JSONfunctions.jObj = jObj;
}
}
LOG CAT
02-20 01:32:12.820: E/JSON Parser(804): Error parsing data org.json.JSONException: Value 1 of type java.lang.Integer cannot be converted to JSONObject
PHP Code
<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['ImageID']) && isset($_POST['ImageDesc']) && isset($_POST['Desc']) && isset($_POST['ImagePath'])) {
$ImageID = $_POST['ImageID'];
$ImageDesc = $_POST['ImageDesc'];
$Desc = $_POST['Desc'];
$ImagePath = $_POST['ImagePath'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE image SET ImageDesc = '$ImageDesc', Desc = '$Desc', ImagePath = '$ImagePath' WHERE ImageID = $ImageID");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
LOG CAT
02-20 01:32:12.820:E/JSON分析器(804):分析数据org.JSON.JSONException时出错:java.lang.Integer类型的值1无法转换为JSONObject
由于echo "UPDATE image
行,输出类似于:
UPDATE image...
{ some: { valid: 'json' }}
这不是有效的JSON。您必须删除echo "UPDATE
才能使输出成为有效的JSON。