dpauxqt1281 2014-11-28 02:13
浏览 88
已采纳

使用android json检查数据库中是否存在数据

I'm using Eclipse to develop an app. I'm trying to check whether the IC exist in database using json. I do the coding and when I run it i got error. the db config is correct coz i have tried the config with other file and it working fine. The plan was:

  1. Input IC in Edit Text : icno_manual
  2. Click button check-in and search for IC in database.
  3. If found, return success
  4. Set the Text View msgResult_manual to "Check-in success" if the TAG_SUCCESS is 1

please help me. here's my xml, java and php.Thanks in advance. table details: rider [ID(PK)- int, name-varchar, IC(UNIQUE)-varchar]

XML file

<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.trialonlistview.MainActivity" >

<TextView
    android:id="@+id/msgResult_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/msgResult_manual"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/icno_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/NRIC_manual"
    android:layout_marginTop="22dp"
    android:ems="10"
    android:inputType="textCapCharacters" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/btnSearch_manual"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/icno_manual"
    android:layout_below="@+id/icno_manual"
    android:layout_marginRight="16dp"
    android:text="@string/btnScan_manual" />

<TextView
    android:id="@+id/NRIC_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/NRIC_manual"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Java edited 1

package com.example.trialonlistview;

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
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.TextView;

public class MainActivity extends Activity {

Button checkIn;
EditText icnotxt;
TextView result;

JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;

private static String icno;

// url to check-in manual
private static String url_manual = "http://192.168.0.25/check/check.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

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

    icnotxt = (EditText)findViewById(R.id.icno_manual);
    checkIn = (Button)findViewById(R.id.btnSearch_manual);
    result = (TextView)findViewById(R.id.msgResult_manual); 

    // check-in button click event
    checkIn.setOnClickListener(new View.OnClickListener() {

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

//manual check-in
//Background Async Task to check-in manually

class CheckIn extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Check-in...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        //add in
        icno = icnotxt.getText().toString();
    }

    //check-in
    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("icno", icno));

        JSONObject json = jsonParser.makeHttpRequest(url_manual,
                "POST", params);

        // check log cat from response
        Log.d("Check-in response", json.toString());

        // check for success tag
        int success;
        try {
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // successfully check-in
                result.setText("Check-in success");
            } else {
                // failed to check-in
                result.setText("Failed");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}
//manual check-in end

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

PHP

<?php
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['icno'])) {
$icno = $_POST['icno'];

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

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

$result = mysql_query("SELECT ID FROM rider WHERE IC = $icno");

// check if found
if (mysql_num_rows($result) > 0) {
    // found
    $response["success"] = 1;
    $response["message"] = "found";

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

    // echoing JSON response
    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);
}
?>

Error edited 1

11-28 10:55:26.802: E/AndroidRuntime(31123): FATAL EXCEPTION: AsyncTask #1
11-28 10:55:26.802: E/AndroidRuntime(31123): java.lang.RuntimeException: An error occured while executing doInBackground()
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.lang.Thread.run(Thread.java:856)
11-28 10:55:26.802: E/AndroidRuntime(31123): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4618)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:839)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:297)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.checkForRelayout(TextView.java:6377)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3577)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3435)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3410)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at com.example.trialonlistview.MainActivity$CheckIn.doInBackground(MainActivity.java:95)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at com.example.trialonlistview.MainActivity$CheckIn.doInBackground(MainActivity.java:1)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
  • 写回答

1条回答 默认 最新

  • drwf69817 2014-11-28 02:26
    关注

    You are accessing UI elements inside doInBackground(). you only can use the UI elements on the Main Thread

    therefore, make String icno Global within the CheckIn class and then move the following line to onPreExecute()

    icno = icnotxt.getText().toString();
    

    EDIT

    return the string to onPostExecute() so the onPostExecute() will handle adding the result text to result textView. So change the following lines within `doInBackground():

    // check for success tag
        int success;
        try {
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // successfully check-in
                return "Check-in success";
            } else {
                // failed to check-in
                return "Failed";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    and change the following in onPostExecute()

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
        result.setText(file_url); //file_url will have the following values either Check-in success or failed
    }
    

    Give me feedback whether this helped you or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀