2016-12-02 21 views
-2

你好,我想从活动得到字符串,并将其设置为一个非活动类,请帮助我,我将我的code.and我需要设置的EditText非活动类网址中的值。帮我如何通过一个活动的背景下,以另一种非活性类在Android中

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); 





    } 

    } 
+1

你可以把评论您要访问和使用的TextView和URL –

+0

是请我添加了一些评论。在urlstring附近的活动,它设置在RestApi类 –

+0

请帮我的 –

回答

0
public class RestAPI { 
      String url; 
// create constructor here 
    public RestAPI(String url){ 
     this.url=url; 
    } 

     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的康恩=(HttpURLConnection类)url.openConnection(); conn.setRequestMethod(“POST”); conn.setConnectTimeout(60000); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter W =新OutputStreamWriter(conn.getOutputStream()); w.write(contents); w.flush(); InputStream istream = conn.getInputStream(); 字符串结果= convertStreamToUTF8String(istream的); 返回结果; }

 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); 
+0

是的我已经添加了这段代码,但它给主要活动,我有错误访问RestApi在另一个活动 –

+0

分享错误代码 –

+0

我有添加的代码和注释那边,我已经得到错误 –

相关问题