简体   繁体   中英

How to send id with json request?

I have two things in my project first is login page which extended with Activity and to check username and password I am using following json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650} .
Now second thing is I am using navigation drawer which is extended with Activity and it uses different Fragment file,now after user log in successfully first fragment will display in which I want to parse some data in List view and for that I am using following json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]} .
So the problem is I need to use user login id 2650 to parse data in List view and want to send it with request in my http URL.

public class LoginPage extends Activity implements OnClickListener{

    private Button btn;
    private EditText user;
    private EditText pass;

    // Progress Dialog
    private ProgressDialog pDialog;
    //JSON parser class
    JSONParser jsonParser = new JSONParser();
    private Button btn1;

    private static final String LOGIN_URL = "http://XXXXX/login";


    private static final String TAG_SUCCESS = "status";
    private static final String TAG_LOGIN = "login";
    private static final String TAG_USERID="user_login_id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_page);

        user=(EditText)findViewById(R.id.loginmailid);
        pass=(EditText)findViewById(R.id.loginpwd);

        btn=(Button)findViewById(R.id.login);
        btn1=(Button)findViewById(R.id.btnreg);
        btn.setOnClickListener(this);



    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.btnreg:
            Intent i = new Intent(this, RegistrationForm.class);
            startActivity(i);
            break;

        default:
                break;
        }

    }
class AttemptLogin extends AsyncTask<String, String, String> {

        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginPage.this);
            pDialog.setMessage("Login..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @SuppressWarnings("unused")
        @Override
        protected String doInBackground(String...args) {
            //Check for success tag
            //int success;
            Looper.prepare();
            String username = user.getText().toString();
            String password = pass.getText().toString();
             try {
                 //Building Parameters


                 List<NameValuePair> params = new ArrayList<NameValuePair>();
                 params.add(new BasicNameValuePair("email", username));
                 params.add(new BasicNameValuePair("password", password));
                 params.add(new BasicNameValuePair("version", "apps"));

                 Log.d("request!", "starting");
                 // getting product details by making HTTP request
                 JSONObject json = jsonParser.makeHttpRequest (
                     LOGIN_URL, "POST", params);

                 //check your log for json response
                 Log.d("Login attempt", json.toString());

                 JSONObject jobj = new JSONObject(json.toString());
                 final String msg = jobj.getString("msg");
                 System.out.println("MSG : " + msg);

                 runOnUiThread(new  Runnable() 
                 {
                    @Override
                    public void run() 
                    {
                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                    } 
                });
                 return json.getString(TAG_SUCCESS);



                //System.out.println(arr.toString());
                //JSONObject arr1  = new JSONObject(json);
                //String ss=arr1.getString("status");
                //System.out.println(ss);
                //System.out.println(arr1.getString("status"));
                 //String date = jObj.getString("status");
                // json success tag
                // success = json.getInt(TAG_SUCCESS);


             }catch (JSONException e) {
                 e.printStackTrace();
             }
             return null;
        }

        // After completing background task Dismiss the progress dialog

        protected void onPostExecute(String file_url) {
            //dismiss the dialog once product deleted
            pDialog.dismiss();
             if(file_url.equals("success")) {

                    // Log.d("Login Successful!", json.toString());
                     Intent i = new Intent(LoginPage.this, MainActivity.class);
                     i.putExtra("user_login_id", TAG_USERID);
                     startActivity(i);


                 }else{
                     //Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
                 }
    }}

}

for fragment class check this https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment

You can send the LOGIN_ID value from Activity as:

Bundle bundle = new Bundle();
bundle.putString("LOGIN_ID", value);

// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment get value in onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("LOGIN_ID");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Edit :

Remove return line, check this code :

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
         String strtext = getArguments().getString("LOGIN_ID"); 
       View rootView = inflater.inflate(R.layout.fragment_home, container, false); 
       aList = new ArrayList<HashMap<String,String>>(); 
       new LoadAlbums().execute(); 
       return rootView;
 }

You dont need NameValuePairs. remove below lines.

         params.add(new BasicNameValuePair("email", username));
         params.add(new BasicNameValuePair("password", password));
         params.add(new BasicNameValuePair("version", "apps"));

create another object.

         JsonObject request = new JsonObject();
         request.put("email", username));
         request.put("password", password));
         request.put("version", "apps"));

You can also add ID in it request.put("ID", ID_VALUE));

ask server developer format of request he will let you know exact format he is parsing on server.

change the code,

boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginPage.this);
        pDialog.setMessage("Login..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @SuppressWarnings("unused")
    @Override
    protected JsonObject doInBackground(String...args) {
        //Check for success tag
        //int success;
        Looper.prepare();
        String username = user.getText().toString();
        String password = pass.getText().toString();
         try {
             //Building Parameters


             List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("email", username));
             params.add(new BasicNameValuePair("password", password));
             params.add(new BasicNameValuePair("version", "apps"));

             Log.d("request!", "starting");
             // getting product details by making HTTP request
             JSONObject json = jsonParser.makeHttpRequest (
                 LOGIN_URL, "POST", params);

             //check your log for json response
             Log.d("Login attempt", json.toString());

             JSONObject jobj = new JSONObject(json.toString());
             final String msg = jobj.getString("msg");
             System.out.println("MSG : " + msg);

             runOnUiThread(new  Runnable() 
             {
                @Override
                public void run() 
                {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                } 
            });
             return jobj;



            //System.out.println(arr.toString());
            //JSONObject arr1  = new JSONObject(json);
            //String ss=arr1.getString("status");
            //System.out.println(ss);
            //System.out.println(arr1.getString("status"));
             //String date = jObj.getString("status");
            // json success tag
            // success = json.getInt(TAG_SUCCESS);


         }catch (JSONException e) {
             e.printStackTrace();
         }
         return null;
    }

    // After completing background task Dismiss the progress dialog

    protected void onPostExecute(JsonObject file_url) {
        //dismiss the dialog once product deleted
        pDialog.dismiss();
         if(jobj.getString("status").equals("success")) {

                // Log.d("Login Successful!", json.toString());
                 Intent i = new Intent(LoginPage.this, MainActivity.class);
                 i.putExtra("user_login_id", jobj.getString("user_login_id"));
                 startActivity(i);


             }else{
                 //Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
             }
}}
class AttemptLogin extends AsyncTask<String, String, String> {

        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginPage.this);
            pDialog.setMessage("Login..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @SuppressWarnings("unused")
        @Override
        protected String doInBackground(String...args) {
            //Check for success tag
            //int success;
            Looper.prepare();
            String username = user.getText().toString();
            String password = pass.getText().toString();
             try {
                 //Building Parameters



                            JSONObject object = new JSONObject();
            object.put("email", username);
            object.put("password", password);
            object.put("version",  "apps");
            String dat = object.toString();
            JSONObject object1 = new JSONObject();

            object1.put("userAuthentication", object);

            String dat1 = object1.toString();
            httppost.setEntity(new StringEntity(dat1, HTTP.US_ASCII));
            httppost.setHeader("Content-type", "application/json;" + HTTP.UTF_8);

            HttpResponse response = httpclient.execute(httppost);
            StatusLine statusLine = response.getStatusLine();

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    content));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            result = builder.toString();





             }catch (JSONException e) {
                 e.printStackTrace();
             }
             return result;
        }

        // After completing background task Dismiss the progress dialog

        protected void onPostExecute(String file_url) {
            //dismiss the dialog once product deleted
            pDialog.dismiss();
             if(result!=null) {

                    // Log.d("Login Successful!", json.toString());
                     Intent i = new Intent(LoginPage.this, MainActivity.class);
                     i.putExtra("user_login_id", TAG_USERID);
                     startActivity(i);


                 }else{
                     //Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
                 }
    }}

}

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