Не могу передать массив на сервер
Добавлено: 10 мар 2015, 00:44
Здравствуйте. Хочу попробовать передать массив на сервер. К примеру список вопросов. Но в итоге имею ошибку:
JSONParser
list.php
MainActivityE/JSON Parser(20752): Error parsing data org.json.JSONException: End of input at character 0 of
Код: Выделить всё
public class MainActivity extends Activity{
private EditText et1, et2, et3; //отсюда берем текст
private Button button1; // при нажатии отправляем
private ArrayList<EditText> list; // тут храниться весь EditText
private JSONArray array; // весь текст который был в EditText потом будет тут
private static final String saveURL = "http://ksupulse.net63.net/list.php"; //ссылка с которой работаем(рабочая)
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText1); //инициализация
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
button1 = (Button) findViewById(R.id.button1);
array = new JSONArray();
list = new ArrayList<EditText>();
list.add(et1); // добавляем весь EditText в ArrayList
list.add(et2);
list.add(et3);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//смотрим размер и добавляем весь текст с list в JSONArray
for(int i = 0; i < list.size(); i++) {
array.put(list.get(i).getText().toString());
}
//запускаем AsyncTask
new SaveQuestions().execute();
}
});
}
private class SaveQuestions extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog;
protected void onPreExecute() {
//код
}
@Override
protected Void doInBackground(String... params) {
//класс, ниже код этого класса
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> save = new ArrayList<NameValuePair>();
save.add(new BasicNameValuePair("listArrayQuestions", array.toString()));
//для проверки сделал тут цикл в array хранятся значения, все выводит
for(int s = 0; s < array.length(); s++){
Log.e("listArrayQuestions" + array, "listArrayQuestions");
}
try{
//передаем
operationLink.makeHttpRequest(saveURL, "POST", save);
}catch(Exception e){Log.e("Exception " + e, "excetion");}
return null;
}
protected void onPostExecute(Void s) {
//код
}
}
}Код: Выделить всё
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) throws JSONException {
// 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, HTTP.UTF_8));
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 jObj;
}
}Код: Выделить всё
<?php
header('Content-Type: application/json; charset=UTF-8');
require 'db_connect.php';
$db = new DB_CONNECT();
$response = array();
$response["qwestions"] = array();
if(isset($_POST['listArrayQuestions'])) {
$listArray = $_POST['listArrayQuestions'];
$list = json_decode($listArray, true);
foreach ($list as $name) {
$result = mysql_query("INSERT INTO `test`(`text`) VALUES ('".$name."')") or die(mysql_error());
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
?>