Android考勤应用

时间:2014-03-16 18:17:36

标签: php android

我是android新手,我还在学习。我正在为我的大学门户网站制作一个关于出勤的Android应用程序..我已经学习了与PHP数据库访问相关的代码并且已经制作了我自己的代码,但不幸的是......当我运行我的项目时......模拟器关闭了说它不起作用,即应用程序已关闭。

我想要它做的就是检查登录页面并说明登录是否成功。 这是主要代码

package com.vasan.msritstudentservice;

import java.util.*;

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

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MSRITMainActivity extends Activity {

Button login;
EditText SID,SPswd;
ProgressDialog PDial = null;

    JSONParser JP = new JSONParser();

    private static String url_login = "http://10.0.2.2/MSRIT Student Info   Handles/MSRIT_login.php";

    private static final String TAG_LOGIN_SUCCESS = "success";
    private static final String TAG_LOGIN_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.msrit_main);
    SID = (EditText) findViewById(R.id.IDEditText);
    SPswd = (EditText) findViewById(R.id.PasswordEditText);     
    login = (Button) findViewById(R.id.LoginButton);

    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            PDial = ProgressDialog.show(getApplicationContext(), "", "Validating user.Please wait...", true);
            new Thread(new Runnable() 
            {
                public void run()
                {
                    login();
                }
            }).start();

        }
    });
}
void login()
{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    JSONObject json = JP.makeHttpRequest(url_login, "GET", params);
    try
    {
        int success = json.getInt(TAG_LOGIN_SUCCESS);
        runOnUiThread(new Runnable()
        {
            public void run()
            {
                PDial.dismiss();
            }
        }); 
        if (success == 1)
        {
            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    Toast.makeText(getApplicationContext(),"Login Success!!", Toast.LENGTH_SHORT).show();
                }
            }); 
        }
        else
        {
            showAlert();                
        }   
    }
    catch(JSONException E)
    {
        PDial.dismiss();
        E.printStackTrace();
    }
}
void showAlert()
{
    MSRITMainActivity.this.runOnUiThread(new Runnable()
    {
        public void run()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MSRITMainActivity.this);
            builder.setTitle("Login Error.");
            builder.setMessage("User not Found.")  
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener()
                   {
                       public void onClick(DialogInterface dialog, int id)
                       {

                       }
                   });                     
            AlertDialog alert = builder.create();
            alert.show();               
        }
    });
}           

}

这是json解析代码

package com.vasan.msritstudentservice;

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.equals.("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.equals("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文件:msrit_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"
android:background="@drawable/app_image"
tools:context=".MSRITMainActivity" >

<TextView
    android:id="@+id/WelcomeTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="24dp"
    android:text="Welcome to MSRIT Student Service"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/RequestTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/WelcomeTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:text="Please enter login details"
    android:textAppearance="?android:attr/textAppearanceMedium" />    

<TextView
    android:id="@+id/IDTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/RequestTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="22dp"
    android:text="Student ID"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/IDEditText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/WelcomeTextView"
    android:layout_below="@+id/IDTextView"
    android:layout_marginTop="14dp"
    android:ems="10"
    android:singleLine="true"
    android:text="STUDENT ID" />

<TextView
    android:id="@+id/PasswordTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Student Password"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/PasswordEditText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/WelcomeTextView"
    android:layout_below="@+id/PasswordTextView"
    android:layout_marginTop="20dp"
    android:ems="10"
    android:singleLine="true"
    android:text="STUDENT PASSWORD" >
    <requestFocus />
</EditText>

<Button
    android:id="@+id/LoginButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/PasswordEditText"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:text="LOGIN" />

</RelativeLayout>

这是程序中使用的php代码

<?php
$response = array();
require_once __DIR__ . '/MSRIT_db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET["studid"]) && $_GET["studpwd"])
{
    $studid = $_GET['studid'];
$studpwd = $_GET['studpwd'];
    $result = mysql_query("SELECT * FROM studentdetails WHERE studid = $attid AND studpwd = $studpwd");
    if (!empty($result))
{
         if (mysql_num_rows($result) > 0)
         {
               $response["success"] = 1;
               $response["message"] = "Login Successful";
               echo json_encode($response);
         }
     else
     {
               $response["success"] = 0;
               $response["message"] = "Login unsuccessful, No Record Found, Please  enter the correct details";
               echo json_encode($response);
         }
    }
else
{
         $response["success"] = 0;
         $response["message"] = "Login unsuccessful, No Record Found, Please enter the correct details";
         echo json_encode($response);
    }
}
else
{
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>

我的清单

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

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.vasan.msritstudentservice.MSRITMainActivity"
        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>

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

我真的想知道我的代码有什么问题asap..thanks

03-17 06:21:02.672: D/dalvikvm(823): GC_CONCURRENT freed 92K, 8% free 2681K/2904K, paused 19ms+3ms, total 70ms
03-17 06:21:02.672: D/dalvikvm(823): WAIT_FOR_CONCURRENT_GC blocked 33ms
03-17 06:21:02.924: D/dalvikvm(823): GC_CONCURRENT freed 314K, 15% free 2769K/3224K, paused 27ms+19ms, total 124ms
03-17 06:21:03.512: D/gralloc_goldfish(823): Emulator without GPU emulation detected.
03-17 06:21:42.571: D/dalvikvm(823): GC_CONCURRENT freed 206K, 11% free 3012K/3352K, paused 72ms+5ms, total 121ms
03-17 06:21:42.571: D/dalvikvm(823): WAIT_FOR_CONCURRENT_GC blocked 21ms
03-17 06:21:42.581: I/dalvikvm-heap(823): Grow heap (frag case) to 3.672MB for 635812-byte allocation
03-17 06:21:42.701: D/dalvikvm(823): GC_FOR_ALLOC freed 57K, 11% free 3576K/3976K, paused 116ms, total 117ms
03-17 06:21:42.821: D/dalvikvm(823): GC_FOR_ALLOC freed 12K, 11% free 3564K/3976K, paused 101ms, total 103ms
03-17 06:21:42.821: I/dalvikvm-heap(823): Grow heap (frag case) to 4.082MB for 500416-byte allocation
03-17 06:21:42.951: D/dalvikvm(823): GC_FOR_ALLOC freed <1K, 10% free 4053K/4468K, paused 119ms, total 119ms
03-17 06:21:43.101: D/dalvikvm(823): GC_CONCURRENT freed 1K, 9% free 4072K/4468K, paused 10ms+87ms, total 150ms
03-17 06:21:43.141: D/AndroidRuntime(823): Shutting down VM
03-17 06:21:43.151: W/dalvikvm(823): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-17 06:21:43.171: E/AndroidRuntime(823): FATAL EXCEPTION: main
03-17 06:21:43.171: E/AndroidRuntime(823): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.app.Dialog.show(Dialog.java:281)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-17 06:21:43.171: E/AndroidRuntime(823):  at com.vasan.msritstudentservice.MSRITMainActivity$1.onClick(MSRITMainActivity.java:45)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.view.View.performClick(View.java:4204)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.view.View$PerformClick.run(View.java:17355)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.os.Handler.handleCallback(Handler.java:725)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.os.Looper.loop(Looper.java:137)
03-17 06:21:43.171: E/AndroidRuntime(823):  at android.app.ActivityThread.main(ActivityThread.java:5041)
03-17 06:21:43.171: E/AndroidRuntime(823):  at java.lang.reflect.Method.invokeNative(Native Method)
03-17 06:21:43.171: E/AndroidRuntime(823):  at java.lang.reflect.Method.invoke(Method.java:511)
03-17 06:21:43.171: E/AndroidRuntime(823):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 06:21:43.171: E/AndroidRuntime(823):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 06:21:43.171: E/AndroidRuntime(823):  at dalvik.system.NativeStart.main(Native Method)
03-17 06:21:51.902: I/Process(823): Sending signal. PID: 823 SIG: 9

0 个答案:

没有答案