1

私は Android プロジェクトに取り組んでおり、ユーザーが EditText ボックスに入力したテキストを取得して、サーバーの SQL テーブルに追加しようとしています。問題は正しい SQL クエリを持っていないことから来ていると思いますが、何を追加しなければならないのかわかりません (SQL に関しては無知です):S

携帯電話でこのアプリを実行すると、何かを入力してデータベースに渡したことを認識しているように見えますが (エラーや例外は表示されません)、実際にはデータベース テーブルには何も追加されません。

私が間違っていた場所についてのアイデアをいただければ幸いです。

JDBC サーバー コード:

public class DBServlet4 extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws IOException, ServletException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;

            try {
                    Class.forName("com.mysql.jdbc.Driver");
                                    con = DriverManager.getConnection(
                                    "jdbc:mysql://localhost:3306/cs2001", "l2g0",
                                    "l2g0");

                    stmt = con.createStatement();

                    stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Students (id int, name varchar(45))");
                    stmt.executeUpdate("INSERT INTO Students (id, name) SELECT * FROM (SELECT '0', 'Michael') AS Temp WHERE NOT EXISTS (SELECT name FROM Students WHERE name = 'Michael') LIMIT 1");

                    //con.commit();

            } catch (SQLException e) {
                    throw new ServletException(e.getMessage());
            } catch (ClassNotFoundException e) {
                    throw new ServletException("JDBC Driver not found.", e);
            } finally {
                    try {
                            if (rs != null) {
                                    rs.close();
                                    rs = null;
                            }
                            if (stmt != null) {
                                    stmt.close();
                                    stmt = null;
                            }
                            if (con != null) {
                                    con.close();
                                    con = null;
                            }
                    } catch (SQLException e) {                        
                    }
            }
            out.close();
    }}

Android コード:

public class MainActivity extends Activity{ 
private static final String ipAddress = "172.31.81.28";
private static final String portNumber = "8085";

protected TextView getText;
protected EditText inputName;
protected List<Student> students;


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

    getText = (TextView) findViewById(R.id.select_output);
    inputName = (EditText) findViewById(R.id.name_input);
}

public void onClick(View v)
{   
    switch (v.getId())
    {
        case R.id.post_button:
        {
            //
            String responseString = "";
            try 
            {
                responseString = new HttpPostTask().execute("" + inputName.getText()).get(10, TimeUnit.SECONDS);
            } 
            catch (InterruptedException e) 
            {
                responseString = "#An Error Occured: InterruptedException";
                e.printStackTrace();
            } 
            catch (TimeoutException e) 
            {
                responseString = "#An Error Occured: TimeoutException";
                e.printStackTrace();
            }
            catch (ExecutionException e) 
            {
                responseString = "#An Error Occured: ExecutionException";
                e.printStackTrace();
            }

            if (responseString.startsWith("#"))
            {
                Toast.makeText(this,
                        responseString.substring(1), Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this,
                        responseString, Toast.LENGTH_SHORT).show();
            }

            break;
        }

        //code for getting data from DB
        case R.id.get_button:
        {
            String responseString = "";
            try 
            {
                responseString = new HttpGetTask().execute("").get(10, TimeUnit.SECONDS);
            } 
            catch (InterruptedException e) 
            {
                responseString = "#An Error Occured: InterruptedException";
                e.printStackTrace();
            } 
            catch (TimeoutException e) 
            {
                responseString = "#An Error Occured: TimeoutException";
                e.printStackTrace();
            }
            catch (ExecutionException e) 
            {
                responseString = "#An Error Occured: ExecutionException";
                e.printStackTrace();
            }

            if (responseString.startsWith("#"))
            {
                Toast.makeText(this,
                        responseString.substring(1), Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this,
                        "Connection Successful", Toast.LENGTH_SHORT).show();

                this.getText.setText(responseString);
                this.students = parseData(responseString, "\n", ":");

                int i = 0;
                for (Student student : students)
                {
                    ++i;
                    System.out.print("[" + i + "] " + student + "\n");
                }
            }

            break;
        }
        default:
        {
            /* Do Nothing */
        }
    }
}

private List<Student> parseData(String input, String caseDelimiter, String fieldDelimiter)
{
    String[] temp = input.split(caseDelimiter);

    LinkedList<Student> students = new LinkedList<Student>();
    for (int i = 0; i < temp.length; i++)
    {
        String[] tempStudent = temp[i].split(fieldDelimiter);
        students.add(new Student(Integer.parseInt(tempStudent[0]), tempStudent[1].trim()));
    }

    return students;
}

private class Student
{
    int id;
    String name;

    public Student(int id, String name)
    {
        this.id = id;
        this.name = name;
    }

    public String toString()
    {
        return "" + id + " - " + name;
    }
}

private class HttpPostTask extends AsyncTask<String, Integer, String>
{
    private static final String ipAddress = "172.31.81.28"; // *** UPDATE THIS ***
    private static final String portNumber = "8085"; // *** UPDATE THIS ***

    @Override
    protected String doInBackground(String... args)
    {
        String responseString = "An Unknown Error Occured";

        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);

        String url = "http://" + ipAddress + ":" + portNumber + "/DB4";
        HttpPost request = new HttpPost(url);

        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "123"));
            nameValuePairs.add(new BasicNameValuePair("username", args[0]));

            request.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            HttpResponse response = client.execute(request);
            HttpEntity resEntityGet = response.getEntity();
            if (resEntityGet != null) 
            {
                responseString = EntityUtils.toString(resEntityGet);
            }

        }
        catch (ClientProtocolException e) 
        {
            responseString = "#An Error Occured: ClientProtocolException";
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            responseString = "#An Error Occured: IOException";
            e.printStackTrace();
        }

        return responseString;
    }
}

private class HttpGetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... args)
    {
        String url = "http://172.31.81.28:8085/DB4";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        String responseString = "";
        try 
        {

            HttpResponse response = client.execute(request);
            HttpEntity resEntityGet = response.getEntity();
            if (resEntityGet != null) 
            {
                responseString = EntityUtils.toString(resEntityGet);
            }

        }
        catch (Exception e) 
        {
            responseString = "#An Error Occured: UndeclaredException";
            e.printStackTrace();
        }

        return responseString;
    }
}   

}
4

1 に答える 1

1

気にしないで、問題は解決しました。別のAsyncTaskクラスを使用しました。

于 2013-03-13T17:48:03.683 に答える