简体   繁体   中英

Android Login screen from Json

I´m newbie on Android and need help.

I have a JSON that looks like this:

    {
    "Id": 1,
    "Name": "user",
    "userId": 4,
    "active": true,
    "ProfileId": 1,
    "Tema": "green",
    "Language": "english",
    "success": true,
    "error": false
}

Json 2:

{"message":"no user or password","success":false,"erroAplicacao":false}

This is my code:

public class MainActivity extends AppCompatActivity {

    EditText usernameWidget;
    EditText passwordWidget;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();

        usernameWidget = (EditText) findViewById(R.id.tv_username);
        passwordWidget = (EditText) findViewById(R.id.tv_password);

    }// END ON CREATE

    public class DownloadTask extends AsyncTask<String, Void, String> {
        String message = "message";
        String loginSuccess;
        String Id = "Id";


        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(inputStream);

                int data = reader.read();

                while (data != -1){
                    char current = (char) data; // each time creates a char current

                    result += current;

                    data = reader.read();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return result;
        }   // END doInBackground


        //Method called when the doInBack is complete
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            try {
                JSONObject jsonObject = new JSONObject(result);
                Log.i("***JSON ITSELF***", result);


                loginSuccess = jsonObject.getString("success");
                Log.i("*****LOGIN SUCCESS*****", loginSuccess);
                message = jsonObject.getString("message");
                Log.i("*****MESSAGE*****", message);
                Id = jsonObject.getString("Id");
                Log.i("*****ID*****", pessoaFisicaId);



            }catch(JSONException e) {
                e.printStackTrace();
            }//  END CATCH

            if (loginSuccess.contains("true")){

                Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
                startActivity(intent);
            }else if (loginSuccess.contains("false")){

                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }// END POST EXECUTE
    }// END Download Task

    public void login(View view) {
        String user = usernameWidget.getText().toString();
        String pass = passwordWidget.getText().toString();

        String stringJSON = "*URL*login=" + user + "&senha=" + pass;
        DownloadTask task = new DownloadTask();
        task.execute(stringJSON);
        Log.i("*****JSON URL*****", stringJSON);

    }// END LOGIN
}// END MAIN

In this order:

                loginSuccess = jsonObject.getString("success");

                message = jsonObject.getString("message");

                Id = jsonObject.getString("Id");

I get the message ("no user or password") from json2 (different url) as a Toast.

If I change the order, lets say, to:

        loginSuccess = jsonObject.getString("success");

        Id = jsonObject.getString("Id");

        message = jsonObject.getString("message");

I don´t get a message. In fact I get the value "message" from the String message at the start of the DownloadTask class.

It seems that the json is only getting two values, the first ones I ask for.

One thing though is that only when the user or password is wrong is that the json has a message (json2):

{"message":"no user or password","success":false,"erroAplicacao":false}

Since my json cant be transformed into an array json (I tried and got error saying this), what should I do?

When you call jsonObject.getString("your_string") , this will throw a JSONException if your string cannot be found. Therefore, the remaining lines in of code in the method will not be executed. Change your LogCat settings to verbose and you should be able to see what's going on.

More info on the getString() method here: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Use GSON

public class User{
  private int Id;
  private String Name;
}

Parse

User user = GSON.fromJSON(jsonString, User.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM