不能似乎从Android发送到JSONObject的远程服务器 [英] Cant seem to send JSONObject from android to remote server
问题描述
我一直在寻找一种方式将数据发送到远程服务器和无法在一个PHP页面似乎得到它的工作...我修改了code从<一个类似的问题href=\"http://stackoverflow.com/questions/15963039/sending-json-data-from-android-to-php-and-writing-to-text-file\">here
但它不still..do工作,我必须把httppost在AsyncTask的什么?我会怎么做呢? code:
公共类GAMEOVER延伸活动{
// TextView的hiscores;
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.gameover); 最后键b =(按钮)findViewById(R.id.button1);
b.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
//执行上的点击动作 Toast.makeText(gameOver.this按钮是pssed $ P $,
Toast.LENGTH_SHORT).show();
尝试{
JSONObject的JSON =新的JSONObject();
json.put(时间戳,1351181576.64078);
json.put(姓名,engine_speed);
json.put(价值,714.0);
POSTDATA(JSON); JSONObject的json2 =新的JSONObject();
json2.put(时间戳,1351181576.7207818);
json2.put(姓名,steering_wheel_angle);
json2.put(价值,11.1633);
POSTDATA(json2);
}赶上(JSONException E){
e.printStackTrace();
} }
});
}公共无效POSTDATA(JSONObject的JSON)抛出JSONException {
HttpClient的HttpClient的=新DefaultHttpClient();
字符串的URL =http://www.mysite.com/s.php;
尝试{
HttpPost httppost =新HttpPost(URL); 清单&LT;&的NameValuePair GT; NVP =新的ArrayList&LT;&的NameValuePair GT;(2);
nvp.add(新BasicNameValuePair(JSON,json.toString())); httppost.setEntity(新UrlEn codedFormEntity(NVP));
HTT presponse响应= httpclient.execute(httppost); 如果(响应!= NULL){
InputStream为= response.getEntity()的getContent()。
//输入流的反应,可以看出加回Android
Toast.makeText(gameOver.this,(CharSequence的)是,
Toast.LENGTH_SHORT).show();
}其他{Toast.makeText(gameOver.this,数据未寄出
Toast.LENGTH_SHORT).show();}
}赶上(例外五){
e.printStackTrace();
}
}}
logcat的:
十一月九日至六日:45:28.986:W / System.err的(30433):android.os.NetworkOnMainThreadException
十一月九日至6日:45:28.986:W / System.err的(30433):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
十一月九日至6日:45:28.986:W / System.err的(30433):在java.net.InetAddress.lookupHostByName(InetAddress.java:385)
十一月九日至6日:45:28.986:W / System.err的(30433):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
十一月九日至6日:45:28.986:W / System.err的(30433):在java.net.InetAddress.getAllByName(InetAddress.java:214)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
十一月九日至6日:45:28.986:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
十一月九日至6日:45:28.986:W / System.err的(30433):在com.example.testgallery.gameOver.postData(gameOver.java:90)
十一月九日至6日:45:28.986:W / System.err的(30433):在com.example.testgallery.gameOver $ 1.onClick(gameOver.java:65)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.view.View.performClick(View.java:4240)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.view.View $ PerformClick.run(View.java:17721)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.os.Handler.handleCallback(Handler.java:730)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.os.Handler.dispatchMessage(Handler.java:92)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.os.Looper.loop(Looper.java:137)
十一月九日至6日:45:28.986:W / System.err的(30433):在android.app.ActivityThread.main(ActivityThread.java:5103)
十一月九日至6日:45:28.986:W / System.err的(30433):在java.lang.reflect.Method.invokeNative(本机方法)
十一月九日至6日:45:28.986:W / System.err的(30433):在java.lang.reflect.Method.invoke(Method.java:525)
十一月九日至6日:45:28.986:W / System.err的(30433):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
十一月九日至6日:45:28.996:W / System.err的(30433):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
十一月九日至6日:45:28.996:W / System.err的(30433):在dalvik.system.NativeStart.main(本机方法)
十一月九日至6日:45:28.996:W / System.err的(30433):android.os.NetworkOnMainThreadException
十一月九日至6日:45:28.996:W / System.err的(30433):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
十一月九日至6日:45:28.996:W / System.err的(30433):在java.net.InetAddress.lookupHostByName(InetAddress.java:385)
十一月九日至6日:45:28.996:W / System.err的(30433):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
十一月九日至6日:45:28.996:W / System.err的(30433):在java.net.InetAddress.getAllByName(InetAddress.java:214)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
十一月九日至6日:45:28.996:W / System.err的(30433):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
十一月九日至6日:45:28.996:W / System.err的(30433):在com.example.testgallery.gameOver.postData(gameOver.java:90)
十一月九日至6日:45:28.996:W / System.err的(30433):在com.example.testgallery.gameOver $ 1.onClick(gameOver.java:71)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.view.View.performClick(View.java:4240)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.view.View $ PerformClick.run(View.java:17721)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.os.Handler.handleCallback(Handler.java:730)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.os.Handler.dispatchMessage(Handler.java:92)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.os.Looper.loop(Looper.java:137)
十一月九日至6日:45:28.996:W / System.err的(30433):在android.app.ActivityThread.main(ActivityThread.java:5103)
十一月九日至6日:45:28.996:W / System.err的(30433):在java.lang.reflect.Method.invokeNative(本机方法)
十一月九日至6日:45:28.996:W / System.err的(30433):在java.lang.reflect.Method.invoke(Method.java:525)
十一月九日至6日:45:28.996:W / System.err的(30433):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
十一月九日至6日:45:28.996:W / System.err的(30433):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
十一月九日至6日:45:28.996:W / System.err的(30433):在dalvik.system.NativeStart.main(本机方法)
您应该使用的AsyncTask ,以使发送数据。我不知道你的PHP页面,但是我将试图解释如何将数据从Android的使用JSON发送到服务器(如果您有任何进一步的问题请参考本教程的 http://www.androidhive.info/2012/05/how-to-connect-android-with-php -mysql / )。您发送三个值到服务器作为POST请求。我想你的PHP文件应该得到的三个变量,并将其插入到数据库中,然后相应地发回数据。
您的PHP文件(我假设你希望将这些值插入到一个名为细节有三列的时间戳,名称,值数据库,然后告诉应用程序的用户数据是否被插入或不。)
insert.php
&LT; PHP //连接到数据库 //声明数组为en code你的回应
$ ARR =阵列(); 如果((使用isset($ _ POST [时间戳]))及及(使用isset($ _ POST [名称]))及及(使用isset($ _ POST [值)))
{
$时间= $ _ POST [时间戳];
$名称= $ _ POST [名称];
$值= $ _ POST [值];
$查询=插入详细信息(时间戳,名称,值)值'$时间,$名称','$价值';
$结果= mysql_query($结果);
如果($结果){
//成功插入到数据库
$常用3 [成功] = 1;
$常用3 [消息] =数据插入成功。 //呼应JSON响应
回声json_en code($ ARR);
}其他{
//没有插入一行
$常用3 [成功] = 0;
$常用3 [消息] =发生错误。 //呼应JSON响应
回声json_en code($ ARR);
}
}其他{
//必填字段缺失
$常用3 [成功] = 0;
$常用3 [消息] =必填字段(s)是失踪; //呼应JSON响应
回声json_en code($ ARR);
}
?&GT;
您GAMEOVER类必须有一个子类whiich必须扩展的AsyncTask 并做JSON插入。
GAMEOVER活动
公共类GAMEOVER延伸活动{
// TextView的hiscores;
JSONParser jsonParser;
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.gameover);最后键b =(按钮)findViewById(R.id.button1);
b.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
//执行上的点击动作 Toast.makeText(gameOver.this按钮是pssed $ P $,
Toast.LENGTH_SHORT).show();
新插入()执行(); }
});
}类插入扩展的AsyncTask&LT;字符串,字符串,字符串&GT;{@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(gameOver.this);
pDialog.setMessage(插入详细..);
pDialog.setIndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}@覆盖
保护字符串doInBackground(字符串...为arg0){ jsonParser =新JSONParser(); //大厦参数
清单&LT;&的NameValuePair GT; PARAMS =新的ArrayList&LT;&的NameValuePair GT;();
params.add(新BasicNameValuePair(时间戳,1351181576.64078));
params.add(新BasicNameValuePair(姓名,engine_speed));
params.add(新BasicNameValuePair(价值,714.0)); //获取JSON对象
JSONObject的JSON = jsonParser.makeHtt prequest(&lt;您的域,名称&gt; /insert.php,POST,则params); //Log.d(\"JSON:,json.toString()); 尝试
{
成功= json.getInt(成功); 如果(成功== 1){
Log.d(查询,数据插入成功);
}其他{
Log.d(查询,不成功的数据submition);
}
}赶上(JSONException E){
Log.d(JSON:,异常);
} 返回null;
}
在 JSONParser 上述类
包装&lt;您的包名称取代;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser {静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;//构造
公共JSONParser(){}//函数得到JSON的网址
//通过HTTP POST或GET方法
公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
清单&LT;&的NameValuePair GT; PARAMS){ //使HTTP请求
尝试{ //检查请求的方法
如果(方法==POST){
//请求方法是POST
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS)); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }否则如果(方法==GET){
//请求方法是GET
DefaultHttpClient的HttpClient =新DefaultHttpClient();
字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
网址+ =? +中的paramString;
HTTPGET HTTPGET =新HTTPGET(URL); HTT presponse HTT presponse = httpClient.execute(HTTPGET);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
} }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj;}
}
I have been searching for a way to send data to a php page on a remote server and cant seem to get it to work...I modified the code from a similar question on here but it doesnt work still..do I have to put the httppost in an asynctask or something? How would I do that? Code:
public class gameOver extends Activity {
//TextView hiscores;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
Toast.makeText(gameOver.this, "button was pressed",
Toast.LENGTH_SHORT).show();
try {
JSONObject json = new JSONObject();
json.put("timestamp", 1351181576.64078);
json.put("name", "engine_speed");
json.put("value", 714.0);
postData(json);
JSONObject json2 = new JSONObject();
json2.put("timestamp", 1351181576.7207818);
json2.put("name", "steering_wheel_angle");
json2.put("value", 11.1633);
postData(json2);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void postData(JSONObject json) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
String URL = "http://www.mysite.com/s.php";
try {
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
nvp.add(new BasicNameValuePair("json", json.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
InputStream is = response.getEntity().getContent();
//input stream is response that can be shown back on android
Toast.makeText(gameOver.this, (CharSequence) is,
Toast.LENGTH_SHORT).show();
}else{ Toast.makeText(gameOver.this, "data Not sent",
Toast.LENGTH_SHORT).show();}
}catch (Exception e) {
e.printStackTrace();
}
}
}
logcat:
09-06 11:45:28.986: W/System.err(30433): android.os.NetworkOnMainThreadException
09-06 11:45:28.986: W/System.err(30433): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-06 11:45:28.986: W/System.err(30433): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-06 11:45:28.986: W/System.err(30433): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-06 11:45:28.986: W/System.err(30433): at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-06 11:45:28.986: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-06 11:45:28.986: W/System.err(30433): at com.example.testgallery.gameOver.postData(gameOver.java:90)
09-06 11:45:28.986: W/System.err(30433): at com.example.testgallery.gameOver$1.onClick(gameOver.java:65)
09-06 11:45:28.986: W/System.err(30433): at android.view.View.performClick(View.java:4240)
09-06 11:45:28.986: W/System.err(30433): at android.view.View$PerformClick.run(View.java:17721)
09-06 11:45:28.986: W/System.err(30433): at android.os.Handler.handleCallback(Handler.java:730)
09-06 11:45:28.986: W/System.err(30433): at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 11:45:28.986: W/System.err(30433): at android.os.Looper.loop(Looper.java:137)
09-06 11:45:28.986: W/System.err(30433): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-06 11:45:28.986: W/System.err(30433): at java.lang.reflect.Method.invokeNative(Native Method)
09-06 11:45:28.986: W/System.err(30433): at java.lang.reflect.Method.invoke(Method.java:525)
09-06 11:45:28.986: W/System.err(30433): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-06 11:45:28.996: W/System.err(30433): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-06 11:45:28.996: W/System.err(30433): at dalvik.system.NativeStart.main(Native Method)
09-06 11:45:28.996: W/System.err(30433): android.os.NetworkOnMainThreadException
09-06 11:45:28.996: W/System.err(30433): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-06 11:45:28.996: W/System.err(30433): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-06 11:45:28.996: W/System.err(30433): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-06 11:45:28.996: W/System.err(30433): at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-06 11:45:28.996: W/System.err(30433): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-06 11:45:28.996: W/System.err(30433): at com.example.testgallery.gameOver.postData(gameOver.java:90)
09-06 11:45:28.996: W/System.err(30433): at com.example.testgallery.gameOver$1.onClick(gameOver.java:71)
09-06 11:45:28.996: W/System.err(30433): at android.view.View.performClick(View.java:4240)
09-06 11:45:28.996: W/System.err(30433): at android.view.View$PerformClick.run(View.java:17721)
09-06 11:45:28.996: W/System.err(30433): at android.os.Handler.handleCallback(Handler.java:730)
09-06 11:45:28.996: W/System.err(30433): at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 11:45:28.996: W/System.err(30433): at android.os.Looper.loop(Looper.java:137)
09-06 11:45:28.996: W/System.err(30433): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-06 11:45:28.996: W/System.err(30433): at java.lang.reflect.Method.invokeNative(Native Method)
09-06 11:45:28.996: W/System.err(30433): at java.lang.reflect.Method.invoke(Method.java:525)
09-06 11:45:28.996: W/System.err(30433): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-06 11:45:28.996: W/System.err(30433): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-06 11:45:28.996: W/System.err(30433): at dalvik.system.NativeStart.main(Native Method)
You should you use AsyncTask to make send the data. I do not know your php page however I will try to explain how to send data to a server from android using JSON (If you have any further problems refer to this tutorial http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/). You are sending three values to the server as a POST request. I think your php file should receive the three variables and insert them into a database and then send back data accordingly.
Your php file (I am assuming you want to insert these values into a database named Details having three columns timestamp,name,value and then tell the app user if the data has been inserted or not.)
insert.php
<?php
//connect to your database
//declare an array to encode your response
$arr = array();
if((isset($_POST["timestamp"]))&&(isset($_POST["name"]))&&(isset($_POST["value"])))
{
$time = $_POST["timestamp"];
$name = $_POST["name"];
$value = $_POST["value"];
$query = "insert into Details(timestamp,name,value) values '$time','$name','$value'";
$result = mysql_query($result);
if ($result) {
// successfully inserted into database
$arr["success"] = 1;
$arr["message"] = "Data successfully inserted.";
// echoing JSON response
echo json_encode($arr);
} else {
// failed to insert row
$arr["success"] = 0;
$arr["message"] = "An error occurred.";
// echoing JSON response
echo json_encode($arr);
}
} else {
// required field is missing
$arr["success"] = 0;
$arr["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($arr);
}
?>
Your class gameOver must have a subclass whiich must extend AsyncTask and do the JSON insertion.
gameOver Activity
public class gameOver extends Activity {
//TextView hiscores;
JSONParser jsonParser;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
Toast.makeText(gameOver.this, "button was pressed",
Toast.LENGTH_SHORT).show();
new Insert().execute();
}
});
}
class Insert extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(gameOver.this);
pDialog.setMessage("Inserting Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
jsonParser = new JSONParser();
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("timestamp",1351181576.64078));
params.add(new BasicNameValuePair("name","engine_speed"));
params.add(new BasicNameValuePair("value", 714.0));
//getting JSON Object
JSONObject json = jsonParser.makeHttpRequest("<your-domain-name>/insert.php", "POST", params);
//Log.d("JSON:",json.toString());
try
{
success = json.getInt("success");
if(success == 1){
Log.d("Query","Data Successfully inserted");
}else{
Log.d("Query","Unsuccessful in data submition");
}
}catch(JSONException e){
Log.d("JSON:","EXCEPTION");
}
return null;
}
The JSONParser class mentioned above is
package <your-package-name>;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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 method
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, "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;
}
}
这篇关于不能似乎从Android发送到JSONObject的远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!