Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中将一个活动的上下文传递给另一个非活动类_Android_Android Activity - Fatal编程技术网

如何在Android中将一个活动的上下文传递给另一个非活动类

如何在Android中将一个活动的上下文传递给另一个非活动类,android,android-activity,Android,Android Activity,你好,我想从活动中获取字符串并将其设置为另一个非活动类。请帮助我添加代码。我需要在非活动类url中设置edittext值。帮帮我 my activity. public class AlertForIp extends AppCompatActivity { String value; private Button mButton; final Context c = this; st

你好,我想从活动中获取字符串并将其设置为另一个非活动类。请帮助我添加代码。我需要在非活动类url中设置edittext值。帮帮我

 my activity. 

     public class AlertForIp extends AppCompatActivity {
            String value;
            private Button mButton;
            final Context c = this;
            static String urlString;
            private static AlertForIp instance;
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.dialog);


                instance = this;
                final EditText input = new EditText(AlertForIp.this);

                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
                //AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
              /*  SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
                final SharedPreferences.Editor editor = prefss.edit();*/
                value = input.getText().toString();
                // Setting Dialog Title
                String urlsss="http://";
                String urls=":1219/Json/Handler.ashx";

// This above url string i need to set in that class
                 urlString = urlsss+value+urls;
               /* editor.putString("stringid", urlString); //InputString: from the EditText
                editor.commit();
        */
                alertDialog.setTitle("WELCOME TO RESTROSOFT");

                // Setting Dialog Message
                alertDialog.setMessage("ENTER YOUR IP");
                //final EditText input = new EditText(this);
                //alertDialog.setView(input);

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
                input.setLayoutParams(lp);

                //input.setText("http://");
                InputFilter[] filters = new InputFilter[1];
                filters[0] = new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end,
                                               android.text.Spanned dest, int dstart, int dend) {
                        if (end > start) {
                            String destTxt = dest.toString();
                            String resultingTxt = destTxt.substring(0, dstart)
                                    + source.subSequence(start, end)
                                    + destTxt.substring(dend);
                            if (!resultingTxt
                                    .matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
                                return "";
                            } else {
                                String[] splits = resultingTxt.split("\\.");
                                for (int i = 0; i < splits.length; i++) {
                                    if (Integer.valueOf(splits[i]) > 255) {
                                        Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
                                        return "";
                                    }
                                }
                            }
                        }
                        return null;
                    }

                };
                input.setFilters(filters);
                //input.setText(ip);
                alertDialog.setView(input); //
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.waiting);

                // Setting Positive "Yes" Button


                alertDialog.setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                /*if(input.getText().length()==0)
                                {
                                  input.setError("Field cannot be left blank.");
                                    dialog.dismiss();
                                }*/

                                String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";

                                if (value.matches(validation))
                                {
                                    Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
                                    Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
                                    startActivity(inten);
                                    // or

                                }
                                else if(!input.getText().toString().equals(""))
                                {
                                    Intent intent = new Intent(AlertForIp.this, Sample.class);

                                    startActivity(intent);

                                    //Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
                                }
                                else
                                {

                                    Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
                                    startActivity(inten);

                                    Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
                                }
                            }



                        });


                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Write your code here to execute after dialog
                                //dialog.cancel();
                                finish();
                            }
                        });

                // closed

                // Showing Alert Message
                alertDialog.show();

            }

            public static Context getContext() {

                RestAPI rss=new RestAPI();
                rss.persistItems(urlString);
                return instance.getApplicationContext();
            }
        }
这是我的无活动课

 public class RestAPI  {

        String urlString;
        //String data;
        public void persistItems(String info) {
            Context context = AlertForIp.getContext();
         /*   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
           data = prefs.getString("stringid", "no id");*/
            urlString=info;
        }

        //private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
        private static String convertStreamToUTF8String(InputStream stream) throws IOException {
            String result = "";
            StringBuilder sb = new StringBuilder();
            try {
                InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
                char[] buffer = new char[4096];
                int readedChars = 0;
                while (readedChars != -1) {
                    readedChars = reader.read(buffer);
                    if (readedChars > 0)
                        sb.append(buffer, 0, readedChars);
                }
                result = sb.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return result;
        }




 private String load(String contents) throws IOException {
        //i want to add that urlstring here;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(60000);
        conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
            w.write(contents);
            w.flush();
            InputStream istream = conn.getInputStream();
            String result = convertStreamToUTF8String(istream);
            return result;
        }


        private Object mapObject(Object o) {
            Object finalValue = null;
            if (o.getClass() == String.class) {
                finalValue = o;
            } else if (Number.class.isInstance(o)) {
                finalValue = String.valueOf(o);
            } else if (Date.class.isInstance(o)) {
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
                finalValue = sdf.format((Date) o);
            } else if (Collection.class.isInstance(o)) {
                Collection<?> col = (Collection<?>) o;
                JSONArray jarray = new JSONArray();
                for (Object item : col) {
                    jarray.put(mapObject(item));
                }
                finalValue = jarray;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                Method[] methods = o.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getDeclaringClass() == o.getClass()
                            && method.getModifiers() == Modifier.PUBLIC
                            && method.getName().startsWith("get")) {
                        String key = method.getName().substring(3);
                        try {
                            Object obj = method.invoke(o, null);
                            Object value = mapObject(obj);
                            map.put(key, value);
                            finalValue = new JSONObject(map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            return finalValue;
        }

        public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
            JSONObject result = null;
            JSONObject o = new JSONObject();
            JSONObject p = new JSONObject();
            o.put("interface", "RestAPI");
            o.put("method", "CreateNewAccount");
            p.put("User_Name", mapObject(User_Name));
            p.put("Password", mapObject(Password));
            o.put("parameters", p);
            String s = o.toString();
            String r = load(s);
            result = new JSONObject(r);
            return result;
        } 
这是我创建restApi实例的另一个活动

public class UserDetailsActivity extends Activity {

    TextView tvFisrtName, tvLastName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_details);
        // Show the Up button in the action bar.
        //setupActionBar();

        tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
        tvLastName=(TextView)findViewById(R.id.tv_lastname);

        Intent i=getIntent();
        String username=i.getStringExtra("User_Name");
        new AsyncUserDetails().execute(username);

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
    {
        String str1;
        @Override
        protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
            JSONObject jsonObj = null;

//here i have error
        RestAPI api = new RestAPI();
        try {

        jsonObj = api.GetUserDetails(params[0]);



            //JSONParser parser = new JSONParser();
            //userDetail = parser.parseUserDetails(jsonObj);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("AsyncUserDetails", e.getMessage());

        }

        return jsonObj;
    }

        @Override
        protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub


            try {

                JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);

                str1=jsonObj.getString("user_id").toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();


        tvFisrtName.setText(str1);





    }

    }
现在您可以直接使用这里的url URL=新的URL字符串; HttpURLConnection conn=HttpURLConnection url.openConnection; conn.setRequestMethodPOST; conn.setConnectTimeout60000; 康涅狄格州塞杜特普特鲁; 康涅狄格州塞多因布图; OutputStreamWriter w=新的OutputStreamWriterconn.getOutputStream; w、 书面内容; w、 齐平; InputStream istream=conn.getInputStream; 字符串结果=convertStreamToUTF8Stringistream; 返回结果; }

        private Object mapObject(Object o) {
            Object finalValue = null;
            if (o.getClass() == String.class) {
                finalValue = o;
            } else if (Number.class.isInstance(o)) {
                finalValue = String.valueOf(o);
            } else if (Date.class.isInstance(o)) {
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
                finalValue = sdf.format((Date) o);
            } else if (Collection.class.isInstance(o)) {
                Collection<?> col = (Collection<?>) o;
                JSONArray jarray = new JSONArray();
                for (Object item : col) {
                    jarray.put(mapObject(item));
                }
                finalValue = jarray;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                Method[] methods = o.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getDeclaringClass() == o.getClass()
                            && method.getModifiers() == Modifier.PUBLIC
                            && method.getName().startsWith("get")) {
                        String key = method.getName().substring(3);
                        try {
                            Object obj = method.invoke(o, null);
                            Object value = mapObject(obj);
                            map.put(key, value);
                            finalValue = new JSONObject(map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            return finalValue;
        }

        public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
            JSONObject result = null;
            JSONObject o = new JSONObject();
            JSONObject p = new JSONObject();
            o.put("interface", "RestAPI");
            o.put("method", "CreateNewAccount");
            p.put("User_Name", mapObject(User_Name));
            p.put("Password", mapObject(Password));
            o.put("parameters", p);
            String s = o.toString();
            String r = load(s);
            result = new JSONObject(r);
            return result;
        } 

你能把评论放在你想访问的地方并使用textview和urlyes吗请检查我是否添加了评论。在urlstring附近的活动中,它在RestApi类中设置。请帮助我解决您的问题。我添加了此代码,但它在主活动中给出了错误,我在另一个活动中访问了RestApi。我添加了代码,并在那里注释我获取了errorRestAPI api=new RestAPIurlString;不工作我在另一个函数RestAPI api=new RestAPIurlString中传递了硬编码字符串;
        private Object mapObject(Object o) {
            Object finalValue = null;
            if (o.getClass() == String.class) {
                finalValue = o;
            } else if (Number.class.isInstance(o)) {
                finalValue = String.valueOf(o);
            } else if (Date.class.isInstance(o)) {
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
                finalValue = sdf.format((Date) o);
            } else if (Collection.class.isInstance(o)) {
                Collection<?> col = (Collection<?>) o;
                JSONArray jarray = new JSONArray();
                for (Object item : col) {
                    jarray.put(mapObject(item));
                }
                finalValue = jarray;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                Method[] methods = o.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getDeclaringClass() == o.getClass()
                            && method.getModifiers() == Modifier.PUBLIC
                            && method.getName().startsWith("get")) {
                        String key = method.getName().substring(3);
                        try {
                            Object obj = method.invoke(o, null);
                            Object value = mapObject(obj);
                            map.put(key, value);
                            finalValue = new JSONObject(map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            return finalValue;
        }

        public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
            JSONObject result = null;
            JSONObject o = new JSONObject();
            JSONObject p = new JSONObject();
            o.put("interface", "RestAPI");
            o.put("method", "CreateNewAccount");
            p.put("User_Name", mapObject(User_Name));
            p.put("Password", mapObject(Password));
            o.put("parameters", p);
            String s = o.toString();
            String r = load(s);
            result = new JSONObject(r);
            return result;
        } 
 RestAPI rss=new RestAPI(urlString );