与用mysql JSON的Andr​​oid连接 [英] Android connection with mysql using json

查看:95
本文介绍了与用mysql JSON的Andr​​oid连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON-MYSQL用在我的服务器名为EMP'一个MySQL表2文本字段[名称和注释]连接..它炒菜锅精..但现在我想店面形象,一个额外的领域...但不知道how..pls帮助..
这是我的follwing code ..

MainActivity.java

 包com.example.jparser;进口的java.io.InputStream;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.entity.ByteArrayEntity;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.BasicHttpParams;
进口org.apache.http.params.HttpConnectionParams;
进口org.apache.http.params.HttpParams;
进口org.json.JSONObject;进口android.annotation.TargetApi;
进口android.app.Activity;
进口android.os.Build;
进口android.os.Bundle;
进口android.support.v4.app.NavUtils;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;公共类AddnewActivity延伸活动{    的EditText名称;
    的EditText意见;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_addnew);
        //显示操作栏中的向上按钮。
        setupActionBar();        按钮保存=(按钮)findViewById(R.id.button1);
        save.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(视图v){            尝试{
            名称=(EditText上)findViewById(R.id.editText1);
            。字符串纳米= name.getText()的toString();
            评论=(EditText上)findViewById(R.id.editText2);
            。字符串COM = comments.getText()的toString();            如果(。等于(NM)||.equals(COM)){            Toast.makeText(getApplicationContext(),空场检测,Toast.LENGTH_SHORT).show();
            }
            其他{                尝试{
                    JSONObject的JSON =新的JSONObject();
                    json.put(名,纳米);
                    json.put(评论,COM);
                    HttpClient的客户端=新DefaultHttpClient();
                    字符串URL =htt​​p://share88.hostzi.com/parser/json_req.php;                    HttpPost要求=新HttpPost(URL);
                    request.setEntity(新ByteArrayEntity(json.toString()的getBytes(UTF8)));
                    request.setHeader(JSON,json.toString());
                    HTT presponse响应= client.execute(请求);
                    HttpEntity实体= response.getEntity();                    如果(实体!= NULL){
                        InputStream的河道= entity.getContent();
                        Toast.makeText(getApplicationContext(),插入,Toast.LENGTH_SHORT).show();
                    }
                name.setText(NULL);
                comments.setText(NULL);
                }赶上(的Throwable t)的{                    Toast.makeText(getApplicationContext(),请求失败:+ t.toString(),Toast.LENGTH_SHORT).show();
                }
            }            }赶上(例外五){}            }
        });    }    / **
     *设置{@link android.app.ActionBar},如果API是可用的。
     * /
    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    私人无效setupActionBar(){
        如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.HONEYCOMB){
            getActionBar()setDisplayHomeAsUpEnabled(真)。
        }
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.addnew,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例android.R.id.home:
            //这个ID重新presents主页或向上按钮。在这种情况下
            //活动,向上按钮显示。使用NavUtils允许用户
            //浏览了在应用结构中的一个级别。对于
            //更多详细信息,请参见Android设计的导航模式:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(本);
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }}

activity_addnew.xml

 <的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:paddingLeft =@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    工具:上下文=。AddnewActivity>    <的EditText
        机器人:ID =@ + ID / editText1
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignLeft =@ + ID / textView1
        机器人:layout_below =@ + ID / textView1
        机器人:layout_marginTop =16DP
        机器人:EMS =10
        安卓的inputType =TEXT/>    <按钮
        机器人:ID =@ + ID /按钮1
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentLeft =真
        机器人:layout_below =@ + ID / editText2
        机器人:layout_marginTop =48dp
        机器人:文字=@字符串/ addnewcontent/>    <的EditText
        机器人:ID =@ + ID / editText2
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentLeft =真
        机器人:layout_below =@ + ID / textView2
        机器人:layout_marginTop =17dp
        机器人:EMS =10
        安卓的inputType =textPostalAddress/>    <的TextView
        机器人:ID =@ + ID / textView2
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignLeft =@ + ID / editText2
        机器人:layout_below =@ + ID / editText1
        机器人:layout_marginTop =48dp
        机器人:文字=@字符串/ addcomments/>    <的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentLeft =真
        机器人:layout_alignParentTop =真
        机器人:layout_marginTop =30dp
        机器人:文字=@字符串/ addname/>< / RelativeLayout的>

AddnewActivity.java

 包com.example.jparser;进口的java.io.InputStream;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.entity.ByteArrayEntity;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.BasicHttpParams;
进口org.apache.http.params.HttpConnectionParams;
进口org.apache.http.params.HttpParams;
进口org.json.JSONObject;进口android.annotation.TargetApi;
进口android.app.Activity;
进口android.os.Build;
进口android.os.Bundle;
进口android.support.v4.app.NavUtils;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;公共类AddnewActivity延伸活动{    的EditText名称;
    的EditText意见;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_addnew);
        //显示操作栏中的向上按钮。
        setupActionBar();        按钮保存=(按钮)findViewById(R.id.button1);
        save.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(视图v){            尝试{
            名称=(EditText上)findViewById(R.id.editText1);
            。字符串纳米= name.getText()的toString();
            评论=(EditText上)findViewById(R.id.editText2);
            。字符串COM = comments.getText()的toString();            如果(。等于(NM)||.equals(COM)){            Toast.makeText(getApplicationContext(),空场检测,Toast.LENGTH_SHORT).show();
            }
            其他{                尝试{
                    JSONObject的JSON =新的JSONObject();
                    json.put(名,纳米);
                    json.put(评论,COM);
                    HttpClient的客户端=新DefaultHttpClient();
                    字符串URL =htt​​p://share88.hostzi.com/parser/json_req.php;                    HttpPost要求=新HttpPost(URL);
                    request.setEntity(新ByteArrayEntity(json.toString()的getBytes(UTF8)));
                    request.setHeader(JSON,json.toString());
                    HTT presponse响应= client.execute(请求);
                    HttpEntity实体= response.getEntity();                    如果(实体!= NULL){
                        InputStream的河道= entity.getContent();
                        Toast.makeText(getApplicationContext(),插入,Toast.LENGTH_SHORT).show();
                    }
                name.setText(NULL);
                comments.setText(NULL);
                }赶上(的Throwable t)的{                    Toast.makeText(getApplicationContext(),请求失败:+ t.toString(),Toast.LENGTH_SHORT).show();
                }
            }            }赶上(例外五){}            }
        });    }    / **
     *设置{@link android.app.ActionBar},如果API是可用的。
     * /
    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    私人无效setupActionBar(){
        如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.HONEYCOMB){
            getActionBar()setDisplayHomeAsUpEnabled(真)。
        }
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.addnew,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例android.R.id.home:
            //这个ID重新presents主页或向上按钮。在这种情况下
            //活动,向上按钮显示。使用NavUtils允许用户
            //浏览了在应用结构中的一个级别。对于
            //更多详细信息,请参见Android设计的导航模式:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(本);
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }}

和我的PHP文件

json_res.php

 < PHP包括connect.php$结果= mysql_query(SELECT * FROM EMP);而($行= mysql_fetch_assoc($结果)){
    $输出[] = $行;
    }    打印(json_en code($输出));
    mysql_close();?>

json_req.php

 < PHP
$ JSON =的file_get_contents('PHP://输入');
$ OBJ = json_de code($ JSON);包括connect.php
的mysql_query(INSERT INTO EMP VALUES('','$ obj-> {'名'},$ obj-方式> {'意见'}'));
mysql_close($ CON);?>


解决方案

按照以下步骤从Android发送图像到服务器

如果您想通过JSON发送图像,那么你需要将其转换为字符串,因为JSON没有直接传输图像

的Andr​​oid

第1步:使用转换你的图像中的字符串的Base64 [哪个连接codeS中的形象为字符串]

第2步:通过转换后的字符串中的JSON。

  JSONObject的JSON =新的JSONObject();
json.put(名,纳米);
json.put(评论,COM);
json.put(形象,convertedString);

在服务器端

第1步接收JSON字符串。($ yourimageString)

第2步德code。使用 base64_de code($ yourimageString)方法的JSON字符串的形象。

第3步现在写这篇文章到文件。你会得到你的形象了。

希望它帮助。

JSON-MYSQL connectivity with 2 text fields [name and comments] in a mysql table named 'emp' in my server .. and it woks fine ..but now I want to store image , with an extra field... but don't know how..pls help.. These is my follwing code..

MainActivity.java

package com.example.jparser;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddnewActivity extends Activity {

    EditText name;
    EditText comments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addnew);
        // Show the Up button in the action bar.
        setupActionBar();

        Button save=(Button) findViewById(R.id.button1);
        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            try{
            name=(EditText) findViewById(R.id.editText1);   
            String nm=name.getText().toString();
            comments=(EditText) findViewById(R.id.editText2);   
            String com=comments.getText().toString();

            if("".equals(nm) || "".equals(com)){

            Toast.makeText(getApplicationContext(), "Empty field detected", Toast.LENGTH_SHORT).show(); 
            }
            else{

                try {
                    JSONObject json = new JSONObject();
                    json.put("name", nm);
                    json.put("comments", com);


                    HttpClient client = new DefaultHttpClient();
                    String url = "http://share88.hostzi.com/parser/json_req.php";

                    HttpPost request = new HttpPost(url);
                    request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
                    request.setHeader("json", json.toString());
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        InputStream instream = entity.getContent();


                        Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show(); 
                    }
                name.setText(null);
                comments.setText(null);    


                } catch (Throwable t) {

                    Toast.makeText(getApplicationContext(),  "Request failed: " + t.toString(), Toast.LENGTH_SHORT).show(); 
                }


            }

            }catch(Exception e){}   

            }
        });

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.addnew, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

activity_addnew.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AddnewActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="text" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="48dp"
        android:text="@string/addnewcontent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="48dp"
        android:text="@string/addcomments" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="30dp"
        android:text="@string/addname" />

</RelativeLayout>

AddnewActivity.java

package com.example.jparser;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddnewActivity extends Activity {

    EditText name;
    EditText comments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addnew);
        // Show the Up button in the action bar.
        setupActionBar();

        Button save=(Button) findViewById(R.id.button1);
        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            try{
            name=(EditText) findViewById(R.id.editText1);   
            String nm=name.getText().toString();
            comments=(EditText) findViewById(R.id.editText2);   
            String com=comments.getText().toString();

            if("".equals(nm) || "".equals(com)){

            Toast.makeText(getApplicationContext(), "Empty field detected", Toast.LENGTH_SHORT).show(); 
            }
            else{

                try {
                    JSONObject json = new JSONObject();
                    json.put("name", nm);
                    json.put("comments", com);


                    HttpClient client = new DefaultHttpClient();
                    String url = "http://share88.hostzi.com/parser/json_req.php";

                    HttpPost request = new HttpPost(url);
                    request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
                    request.setHeader("json", json.toString());
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        InputStream instream = entity.getContent();


                        Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show(); 
                    }
                name.setText(null);
                comments.setText(null);    


                } catch (Throwable t) {

                    Toast.makeText(getApplicationContext(),  "Request failed: " + t.toString(), Toast.LENGTH_SHORT).show(); 
                }


            }

            }catch(Exception e){}   

            }
        });

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.addnew, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

And my PHP files are

json_res.php

<?php

include "connect.php";

$result=mysql_query("SELECT* FROM emp");

while($row=mysql_fetch_assoc($result)){
    $output[]=$row;
    }

    print(json_encode($output));
    mysql_close();

?>

and json_req.php

<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);

include "connect.php";


mysql_query("INSERT INTO emp VALUES ('','".$obj->{'name'}."', '".$obj->{'comments'}."')");
mysql_close($con);

?>

解决方案

Follow the steps to send image from Android to Server

If you want to send image via JSON then you need to convert it to string because JSON doesn't transfer Image directly

Android

STEP 1 : Convert your image in to String using Base64[ Which encodes the image to a string]

STEP 2 : Pass the converted string in JSON.

JSONObject json = new JSONObject(); 
json.put("name", nm);
json.put("comments", com);
json.put("image",convertedString);

In Server Side

STEP 1 Receive the JSON String.($yourimageString)

STEP 2 Decode the JSON string to image using base64_decode ($yourimageString) method.

STEP 3 Now write this in to file. You will get your image now.

Hope it helps.

这篇关于与用mysql JSON的Andr​​oid连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆