首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >http post在android应用程序中不起作用

http post在android应用程序中不起作用
EN

Stack Overflow用户
提问于 2015-12-29 22:48:51
回答 3查看 98关注 0票数 0

我是android开发的新手。我正在尝试创建一个应用程序来扫描二维码字符串,并在web服务器上发布相同的内容。我在错误中收到警告,“MainActivity”中的“post”方法签名不正确,并且在单击post按钮时,我收到错误消息:在定义的android:onClick属性的父级或祖先上下文中找不到post(java.lang.IllegalStateException)方法。

如何解决方法中签名错误的问题?

如何在方法中传递两个变量?

代码语言:javascript
运行
复制
public class MainActivity extends AppCompatActivity {

static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
public String contents;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //set the main content layout of the Activity
    setContentView(R.layout.activity_main);
}

//product qr code mode
public void Scan(View v) {
    try {
        //start the scanning activity from the        com.google.zxing.client.android.SCAN intent
        Intent intent = new Intent(ACTION_SCAN);
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    } catch (ActivityNotFoundException anfe) {
        //on catch, show the download dialog
        showDialog(MainActivity.this, "No Scanner Found", "Download a   scanner code activity?", "Yes", "No").show();
    }
}

//alert dialog for downloadDialog
private static AlertDialog showDialog(final Activity act, CharSequence  title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
    downloadDialog.setTitle(title);
    downloadDialog.setMessage(message);
    downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {

            }
        }
    });
    downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    return downloadDialog.show();
}

public void onActivityResult(int requestCode, int resultCode, Intent intent)     {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");

            EditText resultTxt = (EditText) findViewById(R.id.contents);
            resultTxt.setText(contents);
            resultTxt.setVisibility(View.VISIBLE);
        }

    }

 }

public void post(View view, Intent intent) {

                String contents = intent.getStringExtra("SCAN_RESULT");
                new JSONtask().execute(contents);

            }


    public class JSONtask extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... params) {

      try {

            // 1. URL
            URL url = new URL("http://192.168.1.10:8080/SRNSmartLab/rest/service/storeNEdata");
            final String contents = params[0];
            // 2. Open connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 3. Specify POST method
            conn.setRequestMethod("POST");

            // 4. Set the headers
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            // 5. Add JSON data into POST request body


            //`5.1 Use Jackson object mapper to convert Contnet object into   JSON
            //ObjectMapper mapper = new ObjectMapper();

                // 5.2 Get connection output stream
               DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

            // 5.3 Copy Content "JSON" into
           wr.writeBytes(contents);

            // 5.4 Send the request
            wr.flush();

            // 5.5 close
            wr.close();

            // 6. Get the response
            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 7. Print result
            System.out.println(response.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

}

这是布局代码。

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.lab.smart.smartlabinventry.MainActivity"
    tools:showIn="@layout/activity_main"
    android:background="#143de0">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Scan"
        android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textColor="#faf6f6"
    android:textSize="30sp"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Scan1"
        android:id="@+id/button"
        android:onClick="Scan"
        android:layout_above="@+id/spinner"
        android:layout_toRightOf="@+id/contents"
        android:layout_toEndOf="@+id/contents" />

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_centerVertical="true"
        android:layout_alignRight="@+id/button2"
        android:layout_alignEnd="@+id/button2" />
    <EditText
        android:id="@+id/contents"
        android:editable="false"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/spinner"
        android:textColor="#fdf9f9"
        android:layout_marginTop="15dp"
        android:visibility="gone"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/upload"
        android:id="@+id/button2"
        android:onClick="post"
        android:layout_alignTop="@+id/button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

EN

回答 3

Stack Overflow用户

发布于 2015-12-29 23:54:17

你的错误清楚地定义了你的错误

java.lang.IllegalStateException:在定义的android:onClick属性的父上下文或祖先上下文中找不到方法post(视图)。

您已经从button2调用了post(),它将调用post(View view),您希望调用post(View view, Intent intent).If,您想调用post(View view, Intent intent),然后添加该按钮的clicklistener,并从该按钮调用您的方法。

代码语言:javascript
运行
复制
btnPost.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        post(view,intent);
    }
});

票数 1
EN

Stack Overflow用户

发布于 2015-12-29 23:56:33

How exactly does the android:onClick XML attribute differ from setOnClickListener?

查看上面的答案,然后转到您的声明

代码语言:javascript
运行
复制
 public void post(View view, Intent intent) {

从方法签名中删除第二个参数,至少有一个错误可以解决

票数 0
EN

Stack Overflow用户

发布于 2015-12-30 00:07:02

不能,一个OnClickListener不能有两个参数。

为了解决您的问题,只需将扫描结果存储为成员变量即可,您已有成员变量:

代码语言:javascript
运行
复制
public String contents;

然后,在onActivityResult中,将结果设置为成员变量,而不是局部变量:

代码语言:javascript
运行
复制
  public void onActivityResult(int requestCode, int resultCode, Intent intent)     {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
             //modified:
            contents = intent.getStringExtra("SCAN_RESULT");

            EditText resultTxt = (EditText) findViewById(R.id.contents);
            resultTxt.setText(contents);
            resultTxt.setVisibility(View.VISIBLE);
        }

    }

 }

然后,在post()方法中,只需确保contents不为空:

代码语言:javascript
运行
复制
        public void post(View view) {

            if (contents != null) {
                new JSONtask().execute(contents);
            }

        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34513423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档