2013-11-19 3 views
0

Возможность подключения JSON-MYSQL с двумя текстовыми полями [имя и комментарии] в таблице mysql с именем emp на моем сервере .. и это нормально ... но теперь я хочу сохранить изображение, с дополнительное поле ... но не знаю how..pls помочь .. это мой follwing код ..Android-соединение с mysql с помощью json

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); 
    } 

} 

И мои PHP файлы

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(); 

?> 

и 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); 

?> 
+0

Вы хотите отправить изображение с android и сохранить его в базе данных mysql? – GoCrazy

+0

@Vino .. да, я хочу выбрать изображение из android, а затем отправить его через json и сохранить его в базе данных mysql. Я знаю, что это процесс, но не знаю, как реализовать в моем коде выше. – Brett

ответ

0

Выполните шаги, чтобы отправить изображение с Android на сервер

Если вы хотите отправить изображение с помощью JSON, то вам нужно преобразовать его в строку, так как JSON не передает изображение непосредственно

Android

ШАГ 1: Преобразование изображения в строку, используя для Base64 [который кодирует изображение в строку]

STEP 2: Передайте преобразованную строку в JSON.

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

В стороне сервера

ШАГ 1 Получить JSON строку. ($ YourimageString)

ШАГ 2 Decode строку JSON к изображению, используя base64_decode ($yourimageString) метод.

STEP 3 Теперь напишите это в файле. Теперь вы получите свое изображение.

Надеюсь, это поможет.

+0

thanx для вашего ответа. .. Но я запутался, как создать подборщик изображений в моей форме -> activity_addnew.xml ..пожалуйста, помогите – Brett

+0

Привет Бретт, вы можете выбрать изображение, запустив галерею, как Intent intent = new Intent(); intent.setType ("image/*"); intent.setAction (Intent.ACTION_PICK); startActivityForResult (Intent.createChooser (намерение, «Выбрать изображение»), 100); – sandy

+0

hey imager picker работает отлично спасибо .. всякая штука в порядке, без ошибок, но моя база данных не обновляется с изображением. вот мой код .. iv = (ImageView) findViewById (R.id.imageView1) ; iv.buildDrawingCache(); Bitmap bitmap = iv.getDrawingCache(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress (Bitmap.CompressFormat.PNG, 90, поток); byte [] image = stream.toByteArray(); String img_str = Base64.encodeToString (изображение, 0); и я отправляю img_str как json.put ("img", img_str); и я также редактирую файл php на сервере с $ obj = json_decode ($ json); – Brett

Смежные вопросы