首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用json与mysql的Android连接

问使用json与mysql的Android连接
EN

Stack Overflow用户
提问于 2013-11-19 08:49:52
回答 1查看 1.6K关注 0票数 0

JSON-MYSQL连接,在我的服务器中名为'emp‘的mysql表中有两个文本字段、名称和注释。现在我想用一个额外的字段来存储图像.但我不知道how..pls的帮助..。这是我的密码。

MainActivity.java

代码语言:javascript
复制
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

代码语言:javascript
复制
<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

代码语言:javascript
复制
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);
    }

}

我的PHP文件是

json_res.php

代码语言:javascript
复制
<?php

include "connect.php";

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

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

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

?>

和json_req.php

代码语言:javascript
复制
<?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);

?>
EN

回答 1

Stack Overflow用户

发布于 2013-11-19 09:41:27

遵循从Android发送图像到服务器的步骤

如果要通过JSON发送图像,则需要将其转换为string,因为JSON不直接传输image

Android

步骤1:使用将图像编码为字符串的Base64将图像转换为字符串

步骤2:在JSON中传递转换后的字符串。

代码语言:javascript
复制
JSONObject json = new JSONObject(); 
json.put("name", nm);
json.put("comments", com);
json.put("image",convertedString);

服务器端的

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

步骤2使用base64_decode ($yourimageString)方法将JSON字符串解码为图像。

步骤3现在将其写入文件中。你现在可以得到你的形象了。

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20066941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档