2014-03-03 29 views
0

我寫了下面的代碼,從一個PHP文件中獲得一個簡單的消息,它向我發送了一個json對象,我的代碼中沒有錯誤,PHP代碼運行良好,請你幫我找到是我的代碼:)從JSon得到消息

Java代碼事項:

package com.example.httpclient; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

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.impl.client.DefaultHttpClient; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    TextView myListView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     try{ 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

      //This is our textView element 
      myListView = (TextView) findViewById(R.id.textView1); 

      //Lets try to connect 
      try{ 
       //Create a new client object 
       HttpClient httpclient = new DefaultHttpClient(); 

       //Now post to your demo URL 
       HttpPost httppost = new  HttpPost("http://goldengym.ma/test/test1.php"); 

       //Execute the post and get the response 
       HttpResponse response = httpclient.execute(httppost); 

       //Get the message from the response 
       HttpEntity entity = response.getEntity(); 

       //Get the content of the message 
       InputStream webs = entity.getContent(); 

       //Convert response to string 
       try{ 
        BufferedReader reader = new BufferedReader(new  InputStreamReader(webs, "iso-8859-1"), 8); 

        //Read one line of the response 
        myListView.setText(reader.readLine()); 

        //Slow our inputStream 
        webs.close(); 

       }catch(Exception e){ 
        Log.e("log_tag", "Error converting result " +  e.toString()); 
       }    
      }catch(Exception e){ 
       Log.e("log_tag", "Error in http connection " +  e.toString()); 
      } 
     }catch (Exception e){ 
      Log.e("log_tag", "Error " + e.toString()); 
     } 
    } 

} 

而且有PHP代碼:

<?php 

    $result = 'TEST WORKED, WE GOT CONNECTION'; 

    print json_encode($result); 

?> 

而且有我的logcat:

在主線程取得
03-03 12:35:02.918: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118 

03-03 12:35:04.518: W/PackageManager(1995): Code path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk 

03-03 12:35:04.518: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118 

03-03 12:35:04.518: W/PackageManager(1995): Resource path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk 

03-03 12:35:05.218: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118 

03-03 12:35:05.493: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient 

03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> update package com.example.httpclient 

03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient 

03-03 12:35:05.913: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient 

03-03 12:35:06.188: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.example.httpclient 

03-03 12:35:06.523: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient 

03-03 12:35:07.598: W/DeepLinking(3458): no deep link install data found for com.example.httpclient 

03-03 12:35:07.663: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.example.httpclient 

03-03 12:35:07.703: D/PackageAddedReceiver(2234): package added com.example.httpclient 

03-03 12:35:08.048: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.httpclient 
+0

讓你有沒有在logcat的,但你的TextView是空afre要求? – nikis

+0

感謝您的回覆,我的日誌中沒有任何錯誤,textView只是不顯示任何東西(空) –

+0

你可以發佈你的logtcat –

回答

0
package com.example.httpclient; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
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.impl.client.DefaultHttpClient; 
import android.os.Build; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.annotation.TargetApi; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.TextView; 


public class MainActivity extends Activity { 
    TextView myListView; 

@TargetApi(Build.VERSION_CODES.GINGERBREAD) 
@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //This is our textView element 
    myListView = (TextView) findViewById(R.id.tv); 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 


    //Lets try to connect 
    try{ 
     //Create a new client object 
     HttpClient httpclient = new DefaultHttpClient(); 

     //Now post to your demo URL 
     HttpPost httppost = new HttpPost("http://10.0.2.2/testAndroid/test1.php"); 

     //Execute the post and get the response 
     HttpResponse response = httpclient.execute(httppost); 

     //Get the message from the response 
     HttpEntity entity = response.getEntity(); 

     //Get the content of the message 
     InputStream webs = entity.getContent(); 

     //Convert response to string 
     try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8); 

      //Read one line of the response 
      myListView.setText(reader.readLine()); 

      //Slow our inputStream 
      webs.close(); 

     }catch(Exception e){ 
      Log.e("log_tag", "Error converting result " +  e.toString()); 
     }    
    }catch(Exception e){ 
     Log.e("log_tag", "Error in http connection " +  e.toString()); 
    } 
} 


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

} 

PLz試試這個代碼,它工作正常。應該使用

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

和Manifeast

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

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="19" /> 

    <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="com.provider.testdemo.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> 

+0

使用此代碼它工作正常 –

+0

okey:D謝謝我現在就試試看,我會告訴你的結果:D謝謝 –

+0

一個大感謝的男人:D它的工作:D謝謝你的男人:) –

0
  1. 網絡電話是不允許的(http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
  2. 此外,您在AndroidManifest.xml文件需要<uses-permission android:name="android.permission.INTERNET"/>
  3. 千萬不要使用Exception來處理您的例外。
  4. 此外,我會盡量避免將try-catch放入其他try-catch
+0

你不能在主線程上進行聯網操作,你需要創建自己的線程或使用一個'AsyncTask'(http://developer.android.com/reference/android/os/AsyncTask.html) 爲了能夠進行聯網操作,您還需要在AndroidManifest文件中添加該標籤。 – thomasg

+0

謝謝對於你的回答,對於第二點我已經做了(我在我的AndroidManifest中添加了android.permission.INTERNET行),但我不明白第一點(主線程?:p)你能解釋更多:)謝謝 –

+0

您在項目中輸入的大部分代碼都是在主線程(刷新所有視圖的線程)上完成的。您的網絡操作需要在您自己管理的線程上進行。閱讀該頁面的信息:http://developer.android.com/training/basics/network-ops/index.html – thomasg

0

您無法在主線程上執行互聯網操作。它會給你mainThreadException。 你必須使用Asynctask來完成這些操作。然後只有你能夠從Web服務中獲取數據。

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

你可以使用這個鏈接去了解它是如何工作的。

+0

我不知道如何使用這個asynctask: p我是一個真正的初學者:D你有一個tuto或什麼東西可以解釋如何做到這一點:D –

0

做如下:

public class MyAsyncTask extends AsyncTask<String, String, String> { 
    private TextView myListView; 

    public MyAsyncTask(TextView myListView){ 
     this.myListView = myListView; 
    } 
@Override 
protected String doInBackground(String... params) { 
     String response = null; 
    HttpClient httpclient = new DefaultHttpClient(); 

      //Now post to your demo URL 
      HttpPost httppost = new  HttpPost(params[0]); 

      //Execute the post and get the response 
      HttpResponse response = httpclient.execute(httppost); 

      //Get the message from the response 
      HttpEntity entity = response.getEntity(); 

      //Get the content of the message 
      InputStream webs = entity.getContent(); 

      //Convert response to string 
      try{ 
       BufferedReader reader = new BufferedReader(new  InputStreamReader(webs, "iso-8859-1"), 8); 
       response = reader.readLine(); 
      }catch(Exception e){ 
       Log.e("log_tag", "Error converting result " +  e.toString()); 
      }finally{ 
       webs.close(); 
      } 
     return response; 
} 

@Override 
protected void onPostExecute(String result) { 
    if(result != null){ 
      myListView.setText(result); 
    } 
} 

在你的活動onCreate()

new MyAsyncTask(myListView).execute("http://goldengym.ma/test/test1.php"); 

的AsyncTask的關鍵方法是doInBackground(),它在一個單獨的線程執行冗長的操作,而onPostExecute在主線程上工作。有關更多詳細信息,請參閱AsyncTask documentation。另外,在打電話給服務器之前,你應該首先檢查互聯網是否可用。我沒有在這裏發佈這個部分。希望這可以幫助。