java - 如何将数据传递到字符串中,该字符串将在另一个类中访问?

标签 java android

我一直打算将 co.user_id 传递给 public static String USER_ID,以便可以将 string user_id 中的数据从 onPostExecute 函数发送到另一个类。但是,从另一个类我得到空值,这意味着该值没有发送到该类。我应该如何将我的值存储在字符串中,以便该值也可以在另一个类中访问?

public class connect3 extends AsyncTask<String, Void, String> {
View view;
Activity activity;
public static String USER_ID = " ";
public connect3(Activity activity, View v) {
    this.activity = activity;
    view = v;
}

String convertStreamToString(InputStream is) {
    try {
        return new java.util.Scanner(is).useDelimiter("\\A").next();
    } catch (java.util.NoSuchElementException e) {
        return "";
    }
}
protected String doInBackground(String... arg0) {
    String ipAddress = "http://192.168.1.3/apexStore2/";
    try {
        URL url = new URL(ipAddress +"receipts.php");
        String urlParameters =
                URLEncoder.encode("user_name", "UTF-8") + "=" + 
  URLEncoder.encode(arg0[0], "UTF-8") + "&" +
                        URLEncoder.encode("user_id", "UTF-8") + "=" + 
  URLEncoder.encode("???", "UTF-8");

        HttpURLConnection connection = (HttpURLConnection) 
  url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" +
                Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        //System.out.println(response.toString());

        JSONObject mainObject = new JSONObject(response.toString());
        JSONArray uniObject = mainObject.getJSONArray("results");
        for(int i = 0; i < uniObject.length(); i++) {
            ContactReceipt co = new ContactReceipt();
            JSONObject rowObject = uniObject.getJSONObject(i);
            //EventObject co = new EventObject();
            co.user_id = rowObject.getString("user_id");
            USER_ID = co.user_id;
   System.out.println("hi1" + co.user_id);
   }
        //To further break down JSON
        //JSONObject oneObject = mainObject.getJSONObject("1");
        //String id = oneObject.getJSONObject("id");
        try{

        }
        finally{
            connection.disconnect();
        }
    } catch (Exception e){
        System.out.println(e.toString());
    }
    return USER_ID;
    //return "";
}

protected void onPreExecute(){

}

@Override
protected void onPostExecute(String result){
   // receipt1.user_id = user_id;
   // String search = USER_ID;
   // Intent intent = new Intent(activity.getApplication(),receipt1.class);
    //intent.putExtra(USER_ID, search);
    //activity.startActivity(intent);
    Intent intent = new Intent(activity.getApplication(),receipt1.class);
    intent.putExtra("USER_ID", result);
    activity.startActivity(intent);
}

}

这就是我在另一个类中调用该值的方式。

  Intent intent = getIntent();
    String cats = intent.getStringExtra("USER_ID");

最佳答案

由于有多个 UserId,因此您应该将其传递给您的 Activity,请参阅下面的完整代码:

public class Connect3 extends AsyncTask<String, Void, List<String>> {
    View view;
    Activity activity;
    public static String USER_ID = "yourpackagename.USER_ID";
    private List<String> listUserIds;
    public Connect3(Activity activity, View v) {
        this.activity = activity;
        view = v;
    }

    String convertStreamToString(InputStream is) {
        try {
            return new java.util.Scanner(is).useDelimiter("\\A").next();
        } catch (java.util.NoSuchElementException e) {
            return "";
        }
    }
    protected List<String> doInBackground(String... arg0) {
        String ipAddress = "http://192.168.1.3/apexStore2/";
        try {
            URL url = new URL(ipAddress +"receipts.php");
            String urlParameters =
                    URLEncoder.encode("user_name", "UTF-8") + "=" +
                            URLEncoder.encode(arg0[0], "UTF-8") + "&" +
                            URLEncoder.encode("user_id", "UTF-8") + "=" +
                            URLEncoder.encode("???", "UTF-8");

            HttpURLConnection connection = (HttpURLConnection)
                    url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", "" +
                    Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream (
                    connection.getOutputStream ());
            wr.writeBytes (urlParameters);
            wr.flush ();
            wr.close ();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            //System.out.println(response.toString());

            JSONObject mainObject = new JSONObject(response.toString());
            JSONArray uniObject = mainObject.getJSONArray("result");

            if(uniObject != null && uniObject.length() > 0) {

                listUserIds = new ArrayList<>(uniObject.length());

                for (int i = 0; i < uniObject.length(); i++) {
                    ContactReceipt co = new ContactReceipt();
                    JSONObject rowObject = uniObject.getJSONObject(i);
                    //EventObject co = new EventObject();
                    co.user_id = rowObject.getString("user_id");

                    System.out.println("hi1" + co.user_id);

                    listUserIds.add(co.user_id);
                }
            }

            connection.disconnect();

        } catch (Exception e){
            System.out.println(e.toString());
        }

        return listUserIds;
    }

    protected void onPreExecute(){

    }

    @Override
    protected void onPostExecute(List<String> result){
        // receipt1.user_id = user_id;

        Intent intent = new Intent(activity.getApplication(),receipt1.class);
        if(result != null){
            intent.putStringArrayListExtra(USER_ID, (ArrayList<String>) result);
        }

        activity.startActivity(intent);
    }

}

你会在你的 Activity 类中得到这样的结果

if(getIntent() != null){
   ArrayList<String> listUserIds = getIntent().getStringArrayListExtra(Connect3.USER_ID);
}

关于java - 如何将数据传递到字符串中,该字符串将在另一个类中访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36689860/

相关文章:

Android Studio - 如何创建显示在当前 View 上方的透明 View

java - 递归是如何工作的?

java - 如何在 SQL 中使用可选 WHERE 子句?

JAVAFx TextField 验证十进制值

java - Lombok SuperBuilder继承

java - Android:重写主 Activity 的 onCreate 方法

Java Swing : Issue painting a grid

android - 如何在 Android webRTC 上启用 H264

android - 安装我的 Android 应用程序时出现问题

android - 用于开发 Android 应用程序的良好的基于​​ Android 的 IDE