我的应用程序没有将数据发布到android上的MySQL数据库

时间:2014-09-15 09:31:27

标签: java android mysql json eclipse

我的应用无法将数据发布到Android上的MySQL数据库。

应用程序没有响应,因为我添加了这行代码。

//StrictMode.ThreadPolicy policy = new            StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);

没有这行代码就会崩溃。

这是我的代码。

MainActivity.java

package com.example.testingtesting;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
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 MainActivity extends ActionBarActivity {
    EditText et1,et2,et3;
    Button b;
    InputStream is = null;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        setContentView(R.layout.activity_main);

        et1 = (EditText)findViewById(R.id.editText1);
        et2 = (EditText)findViewById(R.id.editText2);
        et3 = (EditText)findViewById(R.id.editText3);
        b = (Button)findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = "" +et1.getText().toString();
                String age = "" +et2.getText().toString();
                String email = "" +et3.getText().toString();

                List<NameValuePair> list = new ArrayList<NameValuePair>();

                list.add(new BasicNameValuePair("name", name));
                list.add(new BasicNameValuePair("age", age));
                list.add(new BasicNameValuePair("email", email));

                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://10.0.2.2/testing.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(list));
                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();

                    is = entity.getContent();
                    String msg = "Data Entered Succesfully";
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }catch(ClientProtocolException e){
                    Log.e("ClientProtocol", "Log_tag");
                }catch(IOException e){
                    Log.e("Log_tag", "IOException");
                    e.printStackTrace();
                }
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main.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="com.example.testingtesting.MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:hint="Name"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="63dp"
        android:hint="Age"
        android:ems="10" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="73dp"
        android:hint="Address"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp"
        android:text="Submit" />

</RelativeLayout>

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingtesting"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

testing.php

<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db("newdb", $con);

$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];

mysql_query("insert into mytable(name, age, email) values('{$name}','{$age}','{$email}')");
//mysql_close();
?>

没有

的LogCat
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

09-15 09:51:04.629: D/dalvikvm(870): Not late-enabling CheckJNI (already on)
09-15 09:51:05.628: E/Trace(870): error opening trace file: No such file or directory (2)
09-15 09:51:06.998: D/gralloc_goldfish(870): Emulator without GPU emulation detected.
09-15 09:51:07.098: D/dalvikvm(870): GC_CONCURRENT freed 137K, 4% free 4352K/4516K, paused 5ms+3ms, total 198ms
09-15 09:53:27.838: I/Choreographer(870): Skipped 39 frames!  The application may be doing too much work on its main thread.
09-15 09:53:37.089: I/Choreographer(870): Skipped 32 frames!  The application may be doing too much work on its main thread.
09-15 09:53:38.789: D/AndroidRuntime(870): Shutting down VM
09-15 09:53:38.789: W/dalvikvm(870): threadid=1: thread exiting with uncaught exception (group=0x2bd39930)
09-15 09:53:38.828: E/AndroidRuntime(870): FATAL EXCEPTION: main
09-15 09:53:38.828: E/AndroidRuntime(870): android.os.NetworkOnMainThreadException
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
09-15 09:53:38.828: E/AndroidRuntime(870):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-15 09:53:38.828: E/AndroidRuntime(870):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-15 09:53:38.828: E/AndroidRuntime(870):  at libcore.io.IoBridge.connect(IoBridge.java:112)
09-15 09:53:38.828: E/AndroidRuntime(870):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-15 09:53:38.828: E/AndroidRuntime(870):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-15 09:53:38.828: E/AndroidRuntime(870):  at java.net.Socket.connect(Socket.java:842)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-15 09:53:38.828: E/AndroidRuntime(870):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-15 09:53:38.828: E/AndroidRuntime(870):  at com.example.testingtesting.MainActivity$1.onClick(MainActivity.java:65)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.view.View.performClick(View.java:4202)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.view.View$PerformClick.run(View.java:17340)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.os.Handler.handleCallback(Handler.java:725)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.os.Looper.loop(Looper.java:137)
09-15 09:53:38.828: E/AndroidRuntime(870):  at android.app.ActivityThread.main(ActivityThread.java:5039)
09-15 09:53:38.828: E/AndroidRuntime(870):  at java.lang.reflect.Method.invokeNative(Native Method)
09-15 09:53:38.828: E/AndroidRuntime(870):  at java.lang.reflect.Method.invoke(Method.java:511)
09-15 09:53:38.828: E/AndroidRuntime(870):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-15 09:53:38.828: E/AndroidRuntime(870):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-15 09:53:38.828: E/AndroidRuntime(870):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

尝试探索JSON,在php中使用json_encode,以及尝试使用AsyncTask或更好地移动到Google Android Volley Library以保持最新/最快可靠的网络呼叫。

答案 1 :(得分:0)

使用 Asynctask 进行网络通话。如果您的targetsdkversion大于10,您将无法执行任何网络任务。您必须严格使用asynctask for android 3.x或之后。

并且您仍然希望运行此应用程序而不是将您的android:targetSdkVersion降低到10或9,而不是我认为它会起作用。但我建议你切换asynctask。

更多访问:http://aiyazparmar.blogspot.in/2014/04/how-to-post-http-request-to-server-in.html