2014-06-10 34 views
0

我想從android連接到遠程數據庫。我想給一個名字作爲輸入。我的應用程序應該顯示包含該名稱的行。我遵循androidhive教程來實現這一點。我的應用程序打開後,我進入崩潰的名稱請幫我out.My主要活動如下:應用程序按下get按鈕後崩潰。 Android的遠程數據庫

package com.example.androidhive; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class MainActivity extends Activity { 

    EditText branchname; 
    EditText counters; 
    EditText tokensserved; 
    EditText tokensissued; 
    EditText tokenswaiting; 
    Button btnGet; 


    String branch; 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // JSON parser class 
    JSONParser jsonParser = new JSONParser(); 

    // single product url 
    private static final String url_product_detials = "http://10.0.2.2/android/getdata.php"; 


    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_PRODUCT = "product"; 
    private static final String TAG_BRANCH = "branchname"; 
    private static final String TAG_COUNTERS= "counters"; 
    private static final String TAG_SERVED = "tokensserved"; 
    private static final String TAG_ISSUED = "tokenissued"; 
    private static final String TAG_WAITING="tokenswaiting"; 

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

     // save button 
     btnGet = (Button) findViewById(R.id.btnGet); 


     // getting product details from intent 
     Intent i = getIntent(); 

     // getting product id (pid) from intent 
     branch = i.getStringExtra(TAG_BRANCH); 



     // save button click event 


     // Delete button click event 
     btnGet.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // deleting product in background thread 
       new GetProductDetails().execute(); 
      } 
     }); 

    } 

    /** 
    * Background Async Task to Get complete product details 
    * */ 
    class GetProductDetails extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Loading product details. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Getting product details in background thread 
     * */ 
     protected String doInBackground(String... params) { 

      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        // Check for success tag 
        int success; 
        try { 
         // Building Parameters 
         List<NameValuePair> params = new ArrayList<NameValuePair>(); 
         params.add(new BasicNameValuePair("branchname", branch)); 

         // getting product details by making HTTP request 
         // Note that product details url will use GET request 
         JSONObject json = jsonParser.makeHttpRequest(
           url_product_detials, "GET", params); 

         // check your log for json response 
         Log.d("Single Product Details", json.toString()); 

         // json success tag 
         success = json.getInt(TAG_SUCCESS); 
         if (success == 1) { 
          // successfully received product details 
          JSONArray productObj = json 
            .getJSONArray(TAG_PRODUCT); // JSON Array 

          // get first product object from JSON Array 
          JSONObject product = productObj.getJSONObject(0); 

          // product with this pid found 
          // Edit Text 
          branchname = (EditText) findViewById(R.id.branchname); 
          counters = (EditText) findViewById(R.id.counters); 
          tokensserved = (EditText) findViewById(R.id.tokensserved); 
          tokensissued=(EditText) findViewById(R.id.tokensissued);  
          tokenswaiting=(EditText) findViewById(R.id.tokenswaiting); 
          // display product data in EditText 
          branchname.setText(product.getString(TAG_BRANCH)); 
          counters.setText(product.getString(TAG_COUNTERS)); 
          tokensserved.setText(product.getString(TAG_SERVED)); 
          tokensissued.setText(product.getString(TAG_ISSUED)); 
          tokenswaiting.setText(product.getString(TAG_WAITING)); 


         }else{ 
          // product with pid not found 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once got all details 
      pDialog.dismiss(); 
     } 
    } 

} 

我JSONParser

package com.example.androidhive; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
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.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <!-- Name Label --> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:text="Branch Name" 
     android:textSize="17dip" /> 

    <!-- Input Name --> 

    <EditText 
     android:id="@+id/branchname" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:singleLine="true" /> 

    <!-- Price Label --> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:text="counters" 
     android:textSize="17dip" /> 

    <!-- Input Price --> 

    <EditText 
     android:id="@+id/counters" 
     android:layout_width="fill_parent" 
     android:layout_height="21dp" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:ems="10" 
     android:inputType="numberDecimal" 
     android:singleLine="true" > 

     <requestFocus /> 
    </EditText> 

    <!-- Description Label --> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:text="Served" 
     android:textSize="17dip" /> 

    <!-- Input description --> 

    <EditText 
     android:id="@+id/tokensserved" 
     android:layout_width="fill_parent" 
     android:layout_height="22dp" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:gravity="top" 
     android:lines="4" /> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:text="Issued" 
     android:textSize="17dip" /> 

    <!-- Input description --> 

    <EditText 
     android:id="@+id/tokensissued" 
     android:layout_width="fill_parent" 
     android:layout_height="22dp" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:layout_weight="0.00" 
     android:gravity="top" 
     android:lines="4" /> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:text="Waiting" 
     android:textSize="17dip" /> 

    <!-- Input description --> 

    <EditText 
     android:id="@+id/tokenswaiting" 
     android:layout_width="fill_parent" 
     android:layout_height="26dp" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:gravity="top" 
     android:lines="4" /> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <!-- Button Create Product --> 

     <Button 
      android:id="@+id/btnGet" 
      android:layout_width="111dp" 
      android:layout_height="wrap_content" 
      android:text="Get" /> 

    </LinearLayout> 

</LinearLayout> 

這裏logcat:

06-10 17:18:02.184: W/dalvikvm(1607): threadid=1: thread exiting with uncaught exception (group=0xb2a2fba8) 
06-10 17:18:02.204: E/AndroidRuntime(1607): FATAL EXCEPTION: main 
06-10 17:18:02.204: E/AndroidRuntime(1607): Process: com.example.androidhive, PID: 1607 
06-10 17:18:02.204: E/AndroidRuntime(1607): android.os.NetworkOnMainThreadException 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at libcore.io.IoBridge.connect(IoBridge.java:112) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at java.net.Socket.connect(Socket.java:843) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at com.example.androidhive.MainActivity$GetProductDetails$1.run(MainActivity.java:120) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at android.os.Handler.handleCallback(Handler.java:733) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at android.os.Handler.dispatchMessage(Handler.java:95) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at android.os.Looper.loop(Looper.java:136) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at java.lang.reflect.Method.invokeNative(Native Method) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at java.lang.reflect.Method.invoke(Method.java:515) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
06-10 17:18:02.204: E/AndroidRuntime(1607):  at dalvik.system.NativeStart.main(Native Method) 

我的PHP:

<?php 

/* 
* Following code will get single product details 
* A product is identified by product id (pid) 
*/ 

// array for JSON response 
$response = array(); 

// include db connect class 
require_once __DIR__ . '/db_connect.php'; 

// connecting to db 
$db = new DB_CONNECT(); 

// check for post data 
if (isset($_GET["branchname"])) { 
    $branchname = $_GET['branchname']; 

    // get a product from products table 
    $result = mysql_query("SELECT *FROM branches WHERE branchname = $branchname"); 

    if (!empty($result)) { 
     // check for empty result 
     if (mysql_num_rows($result) > 0) { 

      $result = mysql_fetch_array($result); 

      $product = array(); 

      $product["branchname"] = $result["branchname"]; 
      $product["counters"] = $result["counters"]; 
      $product["tokensserved"] = $result["tokensserved"]; 
         $product["tokenissuedd"] = $result["tokensissued"]; 
            $product["tokenswaiting"] = $result["tokenswaiting"]; 

      // success 
      $response["success"] = 1; 

      // user node 
      $response["product"] = array(); 

      array_push($response["product"], $branch); 

      // echoing JSON response 
      echo json_encode($response); 
     } else { 
      // no product found 
      $response["success"] = 0; 
      $response["message"] = "No product found"; 

      // echo no users JSON 
      echo json_encode($response); 
     } 
    } else { 
     // no product found 
     $response["success"] = 0; 
     $response["message"] = "No product found"; 

     // echo no users JSON 
     echo json_encode($response); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

    // echoing JSON response 
    echo json_encode($response); 
} 
?> 

我將非常感謝任何能夠幫助我的人。我已經度過了許多不眠之夜。謝謝。我使用WAMP服務器和phpmyadmin。我的數據庫包含5個領域branchname,計數器,送達,發出,等待。

回答

1

這條線:

runOnUiThread(new Runnable() { 

你甚至沒有運行在後臺線程HttpRequest中,你的主UI線程上運行它。正如@andreasrs所提到的,這在Android中是不允許的。所有httprequests必須在另一個線程中完成。

+0

非常感謝您的建議。但問題出在php。我在開頭添加了錯誤報告(0)並且它工作正常 –

0

應用程序崩潰與您的PHP代碼無關。

問題是Android/Java應用程序。 您正試圖訪問相同線程上的網絡,該網絡繪製用戶界面。這是不好的做法,並且會在您的堆棧跟蹤中看到異常。

要修復它,您可以在AsyncTask中執行網絡請求。一旦您在單獨的線程中進行網絡連接,應用程序不會以同樣的方式崩潰。

參考:http://developer.android.com/reference/android/os/AsyncTask.html

+0

PHP代碼本身應該更新,因爲它很容易被注入。我沒有仔細看過它。但正如答案中所述,通過將網絡操作移動到AsyncTask,應用程序崩潰將得到解決。 – andreasrs

相關問題