单击时自动关闭应用程序 - Android

时间:2015-04-23 20:54:01

标签: android button android-activity

我是Android上的新程序员。 我正在尝试创建一个有2个按钮的应用程序。 如果你点击第一个,我想发送一个HTMLpost。而对于第二个,我想创建一个新的活动。 但是当我点击"是"在第一个对话框上,应用程序关闭。 当我想创建新活动时会发生一些事情。我只需点击第二个,应用程序就会自动关闭。

我无法理解发生了什么事。你能帮助我吗? 谢谢!

这是MainActivity.java:

包com.onur.proje;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    final Context context = this;
    private Button button;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.buttonAlert);

        // add button listener
        button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

            // set title
            alertDialogBuilder.setTitle("Do you want to run it?");

            // set dialog message
            alertDialogBuilder
                .setMessage("Your Choice?")
                .setCancelable(false)
                .setPositiveButton("YES",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        HttpClient httpclient = new DefaultHttpClient();
                          // put the address to your server and receiver file here
                      HttpPost httppost = new HttpPost("http://yoursite/yourPHPScript.php");
                          try {
                             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                                 // message is the parameter we are receiving, it has the value of 1 which is the value that will be sent from your server to your Arduino board
                             nameValuePairs.add(new BasicNameValuePair("message", "1"));
                           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                           httpclient.execute(httppost); // send the parameter to the server
                         } catch (ClientProtocolException e) {
                             // TODO Auto-generated catch block
                         } catch (IOException e) {
                             // TODO Auto-generated catch block
                         }
                          dialog.cancel();
                    }
                  })
                .setNegativeButton("NO",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
        });

        button = (Button) findViewById(R.id.button);

        // Capture button clicks
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {

                // Start NewActivity.class
                Intent myIntent = new Intent(MainActivity.this,
                        NewActivity.class);
                startActivity(myIntent);
            }
        });
}
}

新的Activity.java:

import android.os.Bundle;
import android.app.Activity;

public class NewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from new_activity.xml
        setContentView(R.layout.new_activity);
    }
}

activity_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"
    tools:context="com.onur.proje.MainActivity" >

  <Button
      android:id="@+id/buttonAlert"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="85dp"
      android:text="RUN IT" />

  <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/buttonAlert"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="72dp"
      android:text="Button" />

</RelativeLayout>

new_activity.xml

<?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" >


</LinearLayout>

2 个答案:

答案 0 :(得分:1)

您正在对话框中的UI线程上执行网络请求onClick ...这会产生android.os.NetworkOnMainThreadException,并导致您的应用崩溃。

您应该使用AsyncTask或只是创建一个新线程来在后台执行您的网络请求。

编辑:我刚刚注意到,您正在为两个按钮使用一个变量...因此,您永远不会输入网络请求的逻辑,因为您正在设置对button的新引用变量,指向第二个按钮,带有新的onClickListener ...

答案 1 :(得分:0)

你已经为单个Id写了两个按钮点击监听器.....你已经添加了按钮但没有按钮警报..添加我按钮警报和一个按钮监听按钮另一个按钮警报..我' d

公共类MainActivity扩展Activity {final Context context = this;私人按钮; public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);的setContentView(R.layout.activity_main); button =(Button)findViewById(R.id.buttonAlert); //添加按钮监听器button.setOnClickListener(new OnClickListener(){@Override public void onClick(View arg0){AlertDialog.Builder alertDialogBu​​ilder = new AlertDialog.Builder(context); // set title alertDialogBu​​ilder.setTitle(“你想要吗?运行它?“); //设置对话框消息alertDialogBu​​ilder .setMessage(”Your Choice?“)。setCancelable(false).setPositiveButton(”YES“,new DialogInterface.OnClickListener(){public void onClick(DialogInterface dialog,int id) {HttpClient httpclient = new DefaultHttpClient(); //将地址放到您的服务器和接收器文件中HttpPost httppost = new HttpPost(“http://yoursite/yourPHPScript.php”); try {List nameValuePairs = new ArrayList(2); // message是我们正在接收的参数,它的值为1,它是从服务器发送到Arduino板名称值的值.ValuePairs.add(new BasicNameValuePair(“message”,“1”)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); //将参数发送到服务器} ca tch(ClientProtocolException e){// TODO自动生成的catch块} catch(IOException e){// TODO自动生成的catch块} dialog.cancel(); }。)。setNegativeButton(“NO”,new DialogInterface.OnClickListener(){public void onClick(DialogInterface dialog,int id){//如果单击此按钮,只需关闭//对话框并且不执行任何操作dialog.cancel( );}}); //创建警报对话框AlertDialog alertDialog = alertDialogBu​​ilder.create(); //显示alertDialog.show(); }}; button =(Button)findViewById(R.id.button); // putt另一个我在这里按钮提醒捕获按钮单击button.setOnClickListener(new OnClickListener(){public void onClick(View arg0){//启动NewActivity.class Intent myIntent = new Intent(MainActivity.this,NewActivity.class ); startActivity(myIntent);}}); }}