簡體   English   中英

無法實例化活動(Android)

[英]Unable to instantiate activity (Android)

此應用程序嘗試連接到mysql並將數據插入/更新/刪除到數據庫中,但是在啟動應用程序時,它顯示消息“不幸的是項目已停止”

MainActivity.java

package com.example.testsql;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

 Button btn_select;
 Button btn_insert;
 Button btn_update;
 Button btn_delete;

 TextView tv_res;
 EditText txt_hn;
 EditText txt_name;
 EditText txt_age;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 // ตั้งค่าตัวแปล View
 tv_res = (TextView)findViewById(R.id.tv_res);
 txt_hn = (EditText)findViewById(R.id.txt_hn);
 txt_name = (EditText)findViewById(R.id.txt_name);
 txt_age = (EditText)findViewById(R.id.txt_age);

 btn_select = (Button)findViewById(R.id.btn_select);
 btn_select.setOnClickListener(this);

 btn_insert = (Button)findViewById(R.id.btn_insert);
 btn_insert.setOnClickListener(this);

 btn_update = (Button)findViewById(R.id.btn_update);
 btn_update.setOnClickListener(this);

 btn_delete = (Button)findViewById(R.id.btn_delete);
 btn_delete.setOnClickListener(this);

 }

 @Override
 public void onClick(View v){
 switch(v.getId()){
 case R.id.btn_select:
 {
 select();
 break;
 }
 case R.id.btn_insert:
 {
 insert();
 break;
 }
 case R.id.btn_update:
 {
 update();
 break;
 }
 case R.id.btn_delete:
 {
 delete();
 break;
 }
 }
 }

 public void clsText(){
 txt_hn.setText("");
 txt_name.setText("");
 txt_age.setText("");
 }

 public void insert(){
 try{
 String hn = txt_hn.getText().toString().trim();
 String name = txt_name.getText().toString().trim();
 String age = txt_age.getText().toString().trim();
 if ( hn.equals("") || name.equals("") || age.equals("") ){
 return ;
 }
 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 nameValuePairs.add(new BasicNameValuePair("isAdd","true"));
 nameValuePairs.add(new BasicNameValuePair("hn",hn));
 nameValuePairs.add(new BasicNameValuePair("name",name));
 nameValuePairs.add(new BasicNameValuePair("age",age));
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://locahost/php_set_data.php");//Change IP to you WebServer
 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
 httpclient.execute(httppost);
 clsText();
 }catch(Exception e){
 Log.d("log_err", "Error in http connection " + e.toString());
 }
 }

 public void update(){
 // Your update algorithm
 Toast.makeText(getApplicationContext(), "update",Toast.LENGTH_SHORT).show();
 }

 public void delete(){
 // Your delete algorithm
 Toast.makeText(getApplicationContext(), "delete",Toast.LENGTH_SHORT).show();
 }

 public void select() {
 tv_res.setText("");
 InputStream is = null;
 String js_result = "";
 try {
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://locahost/php_get_data.php");
 HttpResponse response = httpclient.execute(httppost);
 HttpEntity entity = response.getEntity();
 is = entity.getContent();
 } catch (Exception e) {
 Log.d("log_err", "Error in http connection " + e.toString());
 }
 try {
 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line);
 }
 is.close();
 js_result = sb.toString();
 } catch (Exception e) {
 Log.e("log_tag", "Error converting result " + e.toString());
 }
 try {
 final JSONArray jArray = new JSONArray(js_result);
 for (int i = 0; i < jArray.length(); i++) {
 JSONObject jo = jArray.getJSONObject(i);
 String hn = jo.getString("hn");
 String name = jo.getString("name");
 String age = String.valueOf(jo.getInt("age"));
 String date_serv = jo.getString("date_serv");
 Log.d("log",hn+","+name+","+age+","+date_serv);
 tv_res.append(hn+","+name+","+age+","+date_serv+"\n");
 }
 } catch (JSONException e) {
 Log.e("log_tag", "Error parsing data " + e.toString());
 }
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Connect To Mysql Example" />
    <EditText
        android:id="@+id/txt_hn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="HN" >
    </EditText>
    <EditText
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name-Lastname" />
    <EditText
        android:id="@+id/txt_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/btn_insert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Insert" />
        <Button
            android:id="@+id/btn_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select" />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update" />
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />
    </LinearLayout>
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <TextView
                android:id="@+id/tv_res"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.testsql"
 android:versionCode="1"
 android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.INTERNET" />
<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
 <activity
 android:name=".Main"
 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>
</manifest>

php_set_data.php

<?php
header("content-type:text/javascript;charset=utf-8");
$con=mysql_connect('localhost','root','')or die(mysql_error());   // เปลี่ยน localhost เป็น ip ของ mysql server
mysql_select_db('android')or die(mysql_error());
mysql_query("SET NAMES UTF8");
if (isset($_POST)){
    if($_POST['isAdd']=='true'){
        $hn=$_POST['hn'];
        $name=$_POST['name'];
        $age = $_POST['age'];
        $date = date('Y-m-d');
        $sql="INSERT INTO `patient` (`hn`, `name`, `age`, `date_serv`) VALUES ('$hn', '$name', '$age', '$date')";
        mysql_query($sql);
    }
}
mysql_close();
?>

php_get_data.php

<?php
header("content-type:text/javascript;charset=utf-8");
$con=mysql_connect('localhost','root','')or die(mysql_error());  // เปลี่ยน localhost เป็น ip ของ mysql server
mysql_select_db('android')or die(mysql_error());
mysql_query("SET NAMES UTF8");
$sql="SELECT * FROM patient";
$res=mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
    $output[]=$row;
}
print(json_encode($output));
mysql_close();
?>

這是logcat 在此處輸入圖片說明

啟動應用程序時,它顯示消息“不幸的是項目已停止”

因為您沒有在AndroidManifest.xml注冊MainActivity活動,所以請使用.MainActivity而不是.MainAndroidManifest.xml注冊MainActivity活動:

<activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
  <!-- your code here  -->
 </activity>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM