Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from the server and loading new screen using Android

Tags:

android

I am using following code to get data from the Server and if the value from server is GEEK then it will load to next class, but new view is not loading. Can you say what is the problem?

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

                if(Re=="GEEK")
                {
                    Intent i = new Intent();
                    i.setClassName(v.getContext(),"com.httplogin.MainScreen");
                    startActivity(i);

                }
            }
        });
    }

    protected String tryLogin(String mUsername, String mPassword)
    {           
        HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;   
            String response = null;         
            String parameters = "username="+mUsername+"&password="+mPassword;   

            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");
                }
                // Response from server after login process will be stored in response variable.                
                response = sb.toString();

                isr.close();
                reader.close();


            }
            catch(IOException e)
            {
                Toast.makeText(this,e.toString(),0).show();
            }
            return response;
    }
}
like image 599
Alex Mathew Avatar asked Dec 20 '10 06:12

Alex Mathew


People also ask

Which thread is used to fetch data from the server?

That has to be on the MainThread(UIThread). Checkout this link for more info about UIThread in android and how its works. However, you can put the logic or IO operation on different thread asynchronously and then you can put populate the result on UI thread. One approach would be to use AsyncTask.

How does the app get the data that gets shown on the screen?

Users will often send data to your app through the Android Sharesheet or the intent resolver. All received data has a MIME type set by the providing app. There are three ways your app can receive data sent by another app: An Activity with a matching intent-filter tag in the manifest.

How do I transfer data from one android app to another?

Android uses the action ACTION_SEND to send data from one activity to another, even across process boundaries. You need to specify the data and its type. The system automatically identifies the compatible activities that can receive the data and displays them to the user.


3 Answers

Refer this code.............., Use trim function because it eliminates the space in a String..

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(); 
    }
}
like image 155
Sankar Ganesh PMP Avatar answered Oct 04 '22 15:10

Sankar Ganesh PMP


Is it Case Sensitive? You should be using .equalsIgnoreCase() when comparing strings in which the case does not matter and .equals() when it does. Also have you stepped through this and debugged to make sure tryLogin(mUsername, mPassword) was returning the expected value?

like image 30
ninjasense Avatar answered Oct 04 '22 17:10

ninjasense


One of the important things to note about your code is that you should never run long-time operations, such as remote server access (tryLogin() call in your case) from the UI thread. This kind of programming will lead to ANR in your application. For more details about this topic, read this article

Briefly, instead of call to tryLogin from onCreate, create async task

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

Login task should be defined like this:

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);
        }
     }
 }
like image 27
dstefanox Avatar answered Oct 04 '22 16:10

dstefanox