从服务器获取数据并使用 Android 加载新屏幕

Posted

技术标签:

【中文标题】从服务器获取数据并使用 Android 加载新屏幕【英文标题】:Getting data from the server and loading new screen using Android 【发布时间】:2011-05-28 02:44:59 【问题描述】:

我正在使用以下代码从服务器获取数据,如果来自服务器的值为GEEK,那么它将加载到下一个类,但未加载新视图。能说说是什么问题吗?

公共无效 onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); 设置内容视图(R.layout.main); login = (Button) findViewById(R.id.login); 用户名 = (EditText) findViewById(R.id.username); 密码 = (EditText) findViewById(R.id.password); login.setOnClickListener(new OnClickListener() @覆盖 公共无效 onClick(查看 v) 字符串重新; 字符串 mUsername = username.getText().toString(); 字符串 mPassword = password.getText().toString(); Re=tryLogin(mUsername, mPassword); 如果(重新==“极客”) 意图 i = new Intent(); i.setClassName(v.getContext(),"com.httplogin.MainScreen"); 开始活动(一); ); protected String tryLogin(String mUsername, String mPassword) HttpURLConnection 连接; OutputStreamWriter 请求 = null; 网址网址 = 空; 字符串响应 = null; 字符串参数 = "username="+mUsername+"&password="+mPassword; 尝试 url = 新 URL("http://serverspace/script.php"); 连接 = (HttpURLConnection) url.openConnection(); 连接.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream()); request.write(参数); 请求.flush(); 请求.close(); 字符串行 = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) sb.append(line + "\n"); // 登录过程后来自服务器的响应将存储在响应变量中。 响应 = sb.toString(); isr.close(); reader.close(); 捕获(IOException e) Toast.makeText(this,e.toString(),0).show(); 返回响应;

【问题讨论】:

【参考方案1】:

参考此代码........,使用修剪功能,因为它消除了字符串中的空间..

public class HttpLogin extends Activity 
    /** Called when the activity is first created. */
    private Button login;
    private EditText username, password;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        login = (Button) findViewById(R.id.login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
             String Re;
                String   mUsername = username.getText().toString();
                String  mPassword = password.getText().toString();

                Re=tryLogin(mUsername, mPassword);
                Log.d(" Check ","Here");
                Log.d("Re",Re);
                String temp_check=Re.trim();
                if(temp_check.equals("GEEK"))
                
                    Intent i = new Intent();
                    i.setClassName(v.getContext(),"com.httplogin.MainScreen");
                    startActivity(i);

                
                else
                
                 //Toast.makeText(HttpLogin.this,"MAX Returned",0).show();
                 displayAlert(Re);
//                  Intent i = new Intent();
//                     i.setClassName(v.getContext(),"com.san.MainScreen");
//                     startActivity(i);
                
            
        );
    

    protected String tryLogin(String mUsername, String mPassword)
               
      Log.d(" TryLoginCheck ","Here");
        HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;   
            String response = null;   
            String temp=null;
            String parameters = "username="+mUsername+"&password="+mPassword;   
            System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
            Log.d("Parameters",parameters);
            try
            

                url = new URL("http://serverspace/script.php");
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();            
                String line = "";               
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                

                    sb.append(line + "\n");
                
                temp=sb.toString();
                Log.d("Temp",temp);
                // Response from server after login process will be stored in response variable.                
                response = sb.toString();
                Log.d("Response",response);
               Log.d("Sb Value",sb.toString());
                isr.close();
                reader.close();


            
            catch(IOException e)
            
                Toast.makeText(this,e.toString(),0).show();
            
           // Log.d("Response",response);
            return response;
    
    public  void displayAlert(String Re)
    
     new AlertDialog.Builder(this).setMessage(Re)
        .setTitle("Returned Value")  
        .setCancelable(true)  
        .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener()   
           public void onClick(DialogInterface dialog, int whichButton)
            finish();
             
           )  
        .show(); 
    

【讨论】:

【参考方案2】:

区分大小写吗?在比较大小写无关紧要的字符串时,您应该使用 .equalsIgnoreCase() ,而在比较大小写时应该使用 .equals() 。您是否也已逐步完成并调试以确保 tryLogin(mUsername, mPassword) 返回预期值?

【讨论】:

if(Re.equals("GEEK"))... 在这里阅读更多-> developer.android.com/reference/java/lang/String.html【参考方案3】:

关于您的代码需要注意的重要一点是,您永远不应该从 UI 线程运行长时间的操作,例如远程服务器访问(在您的情况下是 tryLogin() 调用)。这种编程会导致您的应用程序出现 ANR。有关此主题的更多详细信息,请阅读this article

简单地说,不是从 onCreate 调用 tryLogin,而是创建异步任务

new LoginTask().execute(mUsername, mPassword);

登录任务应该这样定义:

private class LoginTask extends AsyncTask<string, void,="" String=""> 
     protected String doInBackground(String... login) 
         return tryLogin((login[0],login[1]);
     

     protected void onPostExecute(String result) 
        if(result.equalsIgnoreCase("GEEK"))
        
            Intent i = new Intent();
            i.setClassName(v.getContext(),"com.httplogin.MainScreen");
            startActivity(i);
        
     
 

【讨论】:

见我上面在我的回答中添加的例子。

以上是关于从服务器获取数据并使用 Android 加载新屏幕的主要内容,如果未能解决你的问题,请参考以下文章

如何在 kivymd 功能开始时显示加载屏幕?

javascript函数调用以获取数据并在页面加载时显示到屏幕

Android Paging 3 - 从 PagingData<T> 对象获取数据列表

Flutter 在使用 StreamBuilder 从 firebase 加载数据之前显示红色错误屏幕,如何解决?

使用子视图中的数据重新加载 tableview

Flutter:如何在加载页面之前从 Api 获取数据 [关闭]