2016-02-13 89 views
1

我試圖創造一個我想我的應用程序連接到一個網絡服務器,我有一個數據庫名爲akshaynsit1_pathaniswaad並在數據庫中,我有一個名爲表的簡單Android應用Android應用連接到Web服務器表格1。在這個表中我有3列ID(INT自動遞增的主鍵),姓名(VARCHAR(30)),地址爲varchar(30).I'm創建一個簡單註冊頁面,用戶將增加他的名字和地址,這個名稱和地址將通過郵政方式保存到我的網絡服務器。 我的MainActivity.java如下使用POST方法

package com.example.akshay007.sample;

import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

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 java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.URL; 
import java.net.URLConnection; 
import java.net.URLEncoder; 
import java.util.ArrayList; 
import java.util.List; 

public class MainActivity extends AppCompatActivity { 

    EditText ed1,ed2; 
    TextView tv; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     ed1=(EditText)findViewById(R.id.editText); 
     ed2=(EditText)findViewById(R.id.editText2); 
     tv=(TextView)findViewById(R.id.textView2); 
    } 

    public void insert(View view){ 
     String name = ed1.getText().toString(); 
     String add = ed2.getText().toString(); 

     insertToDatabase(name,add); 
    } 

    private void insertToDatabase(String name, String add){ 
     class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { 
      @Override 
      protected String doInBackground(String... params) { 
       String paramUsername = params[0]; 
       String paramAddress = params[1]; 
       try{ 
        String name = paramUsername; 
        String address = paramAddress; 

        String link="http://http://pathaniswaad.com/android_akshay/post.php"; 
        String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8"); 
        data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8"); 

        URL url = new URL(link); 
        URLConnection conn = url.openConnection(); 

        conn.setDoOutput(true); 
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

        wr.write(data); 
        wr.flush(); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

        StringBuilder sb = new StringBuilder(); 
        String line = null; 

        // Read Server Response 
        while((line = reader.readLine()) != null) 
        { 
         sb.append(line); 
         break; 
        } 
        return sb.toString(); 
       } 
       catch(Exception e){ 
        return new String("Exception: " + e.getMessage()); 
       } 
       //return "success"; 
      } 

      @Override 
      protected void onPostExecute(String result) { 
       super.onPostExecute(result); 

       Toast.makeText(getApplicationContext(), "yo bro", Toast.LENGTH_LONG).show(); 
       //TextView textViewResult = (TextView) findViewById(R.id.textViewResult); 
       //textViewResult.setText("Inserted"); 
       //tv.setText("ya brah.."); 
      } 
     } 
     SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); 
     sendPostReqAsyncTask.execute(name, add); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.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(); 

     //noinspection SimplifiableIfStatement 
     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:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

    <EditText 
     android:layout_width="300dp" 
     android:layout_height="wrap_content" 
     android:id="@+id/editText" 
     android:layout_alignParentTop="true" 
     android:hint="name" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="121dp" /> 

    <EditText 
     android:layout_width="300dp" 
     android:layout_height="wrap_content" 
     android:id="@+id/editText2" 
     android:hint="address" 
     android:layout_below="@+id/editText" 
     android:layout_centerHorizontal="true" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Signup" 
     android:id="@+id/button" 
     android:layout_below="@+id/editText2" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="56dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Merchant Signup" 
     android:id="@+id/textView" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="44dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="New Text" 
     android:id="@+id/textView2" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" /> 
</RelativeLayout> 

的AndroidManifest.xml如下:

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

    <uses-permission android:name="android.permission.INTERNET"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/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> 

我post.php中腳本如下

<?php 
$con = mysqli_connect("65.50.265.181:336","jfjtyfyfhjfjdy","uitytityut67","akshaynsit1_pathaniswaad"); 

if (mysqli_connect_errno($con)) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 
else 
{ 
    echo"connection successful <br>"; 
} 
$name = $_POST['name']; 
$address = $_POST['address']; 
$result = mysqli_query($con,"insert into table1 (name,addr) values ('$name','$address')"); 
if(mysqli_query($con,$sql)){ 
    echo 'success'; 
    } 
    else{ 
    echo 'failure'; 
    } 
    mysqli_close($con); 
?> 

請幫任何形式的幫助,將不勝感激!!!!!!!!!!

+0

有什麼問題? –

+0

我的應用程序無法連接到網絡服務器,並且用戶填入應用程序的數據沒有被存儲在網絡服務器中。問題發生在您的logcat的MainActivity.java – akshay

+0

方法insertToDatabase(String name,String add)的某處。 ... –

回答

0

如果你不已經有這個在您的清單文件中,<application>部分之前添加:

<uses-permission android:name="android.permission.INTERNET" /> 

另外,我注意到,你的鏈接,在代碼中,是

http://http://pathaniswaad.com/android_akshay/post.php 

嘗試更改爲

http://pathaniswaad.com/android_akshay/post.php 

由於其他用戶也指出,您需要附加參數。有一種更好的方式來做到這一點使用循環J HttpAsyncClient:

添加到您的gradle這個編譯:

compile 'com.loopj.android:android-async-http:1.4.9' 

這裏是我創建與GitHub上的作業使用這個類,你可以爲你的用途修改:

import com.loopj.android.http.AsyncHttpClient; 
import com.loopj.android.http.AsyncHttpResponseHandler; 
import com.loopj.android.http.RequestParams; 

public class AsyncRestClient { 

    private static final String BASE_URL = "https://jobs.github.com/positions"; 
    private static final String JSON_RESPONSE_APPEND = ".json"; 
    private static final AsyncHttpClient client = new AsyncHttpClient(); 

    public static void getPositions(RequestParams params, AsyncHttpResponseHandler responseHandler) { 
     get(JSON_RESPONSE_APPEND, params, responseHandler); 
    } 

    private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { 
     client.get(getAbsoluteUrl(url), params, responseHandler); 
    } 

    private static String getAbsoluteUrl(String relativeUrl) { 
     return BASE_URL + relativeUrl; 
    } 
} 

這裏是一段代碼,我使用這個類:

RequestParams params = jobRequested.getRequestParams(); 
    AsyncRestClient.getPositions(params, getPositionsResponseHandler); 

呦你需要編寫自己的響應處理程序。如果你想看到所有的代碼,我已經在GitHub上(這是在積極發展)這個項目,你可以看到我是如何寫的響應處理程序和回調的答覆:

https://github.com/JenniferVanderputten/GitHubJobs

+0

我已經在我的清單文件中添加了Internet權限..........你可以看到上面的代碼。 – akshay

+0

我更新了答案,嘗試了另一件事 - 不確定是否收到編輯回覆的通知,因此我添加了此評論。 – JenVander

0

兩件事需要固定:

  1. 您的文章網址鏈接看起來不正確:

    http://http://pathaniswaad.com/android_akshay/post.php

「http://」被使用了兩次。將其更改爲:

http://pathaniswaad.com/android_akshay/post.php 
  • 您忘記到PARAMS追加到網址:

    String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8"); 
    data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8"); 
    
    link += "?"+data; //add this line here 
    
    URL url = new URL(link); 
    
  • 修復這些2,然後再試一次。您還應該通過直接在您的瀏覽器中使用虛構網址來測試您的PHP。這樣就可以確保PHP本身沒有問題。

    祝你好運。