我有一个字符串数组,我需要将数组数据传递给php文件。接受的数据(php)应存储在数据库中。 我有一个文件,我有多个复选框。选中一些复选框后,我想将所选数据传递给php。 我无法弄到错误的地方。
这是我的代码..
第一个文件:callplanactivity.java
public class CallplanActivity extends Activity implements
OnItemSelectedListener {
ListView lv;
Context context;
Spinner city;
ImageButton done;
ProgressDialog pDialog;
private ArrayList<City> cityList;
JSONParser jParser = new JSONParser();
JSONArray doctors_info;
ListView listview;
ListViewAdapter adapter, adaper2;
String cityselected,username;
ArrayList<Doclist> doclists;
List<String> cities = new ArrayList<String>();
private String URL_CITY = "http://10.0.2.2/android_login_api/select_city.php";
private String URL_DOCTORS = "http://10.0.2.2/android_login_api/select_doctors.php";
private static final String TAG_DOCDETAILS = "doctors_details";
static final String TAG_DOC_NAME = "doc_name";
static final String TAG_DOC_QUALI = "qualification";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callplan);
Intent i=getIntent();
username=i.getStringExtra("username");
// Log.d("callplan", username);
doclists = new ArrayList<Doclist>();
city = (Spinner) findViewById(R.id.city_spinner);
listview = (ListView) findViewById(R.id.listview);
done = (ImageButton) findViewById(R.id.done);
adapter = new ListViewAdapter(CallplanActivity.this, doclists);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
cityList = new ArrayList<City>();
city.setOnItemSelectedListener(this);
new GetCity().execute();
done.setOnClickListener(new OnClickListener() {
@SuppressWarnings("null")
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// StringBuffer responseText = new StringBuffer();
ArrayList<Doclist> doclistarray = adapter.doclist;
String[] outputStrArr = new String[doclistarray.size()];
//String[] outputStrArr = null;
//String[] outputStrArr2= new String[doclistarray.size()];
for (int i = 0; i < doclistarray.size(); i++) {
Doclist dc = doclistarray.get(i);
if (dc.isSelected()) {
// Log.d("dc", "" + dc.docname);
outputStrArr[i] = dc.docname;
Log.d("sagar", "" + outputStrArr[i]);
Intent intent=new Intent(CallplanActivity.this,CallplanEnd.class);
intent.putExtra("selectedItems", outputStrArr);
startActivity(intent);
}
else {
// Log.d("sagar not selected", "" + outputStrArr[i]);
}
}
}
});
}
private void populateSpinner() {
// txtCategory.setText("");
for (int i = 0; i < cityList.size(); i++) {
cities.add(cityList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cities);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
city.setAdapter(spinnerAdapter);
}
private class GetCity extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CallplanActivity.this);
pDialog.setMessage("Fetching cities..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CITY,
ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("doctors_details");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
City cat = new City(catObj.getString("city"));
cityList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.callplan, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// new GetCategories().execute();
Spinner city1 = (Spinner) parent;
if (city1.getId() == R.id.city_spinner) {
cityselected = cities.get(position);
Toast.makeText(getApplicationContext(), cityselected,
Toast.LENGTH_LONG).show();
new GetDoctorsDetails().execute();
} else {
Toast.makeText(getApplicationContext(),
"Please Select City from Dropdown Box", Toast.LENGTH_LONG)
.show();
}
}
class GetDoctorsDetails extends AsyncTask<String, String, JSONObject> {
JSONObject jsonObject;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
String city_name = cityselected.toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("city", city_name));
jsonObject = jParser.makeHttpRequest(URL_DOCTORS, "POST", params1);
Log.e("Response: ", "> " + jsonObject.toString());
return jsonObject;
}
@Override
protected void onPostExecute(JSONObject json) {
adapter.doclist.clear();
pDialog.dismiss();
if (json != null) {
try {
doctors_info = json.getJSONArray(TAG_DOCDETAILS);
Log.e("Response: ", "> " + doctors_info.toString());
for (int i = 0; i < doctors_info.length(); i++) {
JSONObject c = doctors_info.getJSONObject(i);
Doclist dl = new Doclist();
String doc_name = c.getString(TAG_DOC_NAME);
String qualification = c.getString(TAG_DOC_QUALI);
dl.setdocname(doc_name);
dl.setquali(qualification);
doclists.add(dl);
}
} catch (JSONException e) {
e.printStackTrace();
}
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
从复选框中选择一些值后,数据将传递到另一个文件。
第二个文件:callplanend.java
public class CallplanEnd extends Activity {
String[] str,str1;
ServiceHandler servicehandler;
JSONParser jsonparser;
String username;
private String url_callplanends = "http://10.0.2.2/android_login_api/callplanends.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent intt = getIntent();
username = intt.getStringExtra("username");
// Log.d("detailing", username);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
for (int i = 0; i < resultArr.length; i++) {
if (resultArr[i] != null) {
str = resultArr;
Log.d("sagar#######", "" + str[i]);
Toast.makeText(getApplicationContext(), ""+str, Toast.LENGTH_LONG).show();
}
else {
// str1[i]=resultArr[i];
}
}
new detailparser().execute();
}
public class detailparser extends
AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jobject=new JSONObject();
String[] docs = str;
String id = "1";
String user_id = "2";
String username = "sagar";
Log.d("size",""+docs.length);
List<NameValuePair> dc = new ArrayList<NameValuePair>();
for (int k = 0; k < docs.length; k++) {
if (docs[k] != null) {
// Log.d("size==--==",""+docs.length);
// Log.d("size==",""+dc.size());
Log.d("id", "" + id);
Log.d("user_id", "" + user_id);
Log.d("username", "" + username);
Log.d("docs name", "" + docs[k]);
dc.add(new BasicNameValuePair("docslist[]", docs[k]));
dc.add(new BasicNameValuePair("id", id));
dc.add(new BasicNameValuePair("user_id", user_id));
dc.add(new BasicNameValuePair("username", username));
try {
JSONObject json = jsonparser.makeHttpRequest(
url_callplanends, "POST", dc);
Log.d("Json-data", json.toString());
try {
int success = json.getInt("success");
if (success == 1) {
/*
* Intent i = new Intent(getApplicationContext(),
* MaindisplayActivity.class); startActivity(i);
*/
// finish();
/*Log.d("id", "" + id);
Log.d("user_id", "" + user_id);
Log.d("username", "" + username);
Log.d("docs", "" + docs[k]);*/
Log.d("success", json.toString());
} else {
Log.d("failed", "upload failed");
}
} catch (JSONException e) {
e.printStackTrace();
}
}catch(NullPointerException e){
e.printStackTrace();
}
}
else {
Log.d("null", "null"+k);
}
}
return null;
}
}
}
这是我的 php代码来接受来自android的数组值.. 所选的值应该传递给这个php文件,它们必须存储在数据库中。
<?php
$response = array();
if (isset($_POST['id']) &&
isset($_POST['user_id']) &&
isset($_POST['username'])
&& isset ($_POST['docslist'])
) {
$id=$_POST['id'];
$user_id=$_POST['user_id'];
$username=$_POST['username'];
$docslist = $_POST['docslist'];
$docarray=json_decode($docslist);
require_once 'include/DB_Connect.php';
$db = new DB_Connect();
$query= mysql_query("INSERT INTO selected_docs(id,user_id,username,docname) VALUES('$id','$user_id','$username','$docarray')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"]="successfully inserted data";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"]="Insertion failed ";
// echoing JSON response
echo json_encode($response);
}
}
else {
$response["success"] = 0;
$response["message"]="Connection Failure";
// echoing JSON response
echo json_encode($response);
}
?>
答案 0 :(得分:0)
我不知道php但是在android中你可以使用循环逐个添加数组的值或者使用类似这个链接的解决方案:
Passing String array to PHP as POST
答案 1 :(得分:0)
我没有在php中发送数组并解码该数组,而是将数组转换为字符串并将该值传递给php。
以下是我对代码所做的更改..
dc.add(new BasicNameValuePair("docslist[]", docs.ArraytoString));
刚刚更改了这一行,并将Array转换为字符串并发送。
现在它工作正常,发送的数据被插入到数据库中。