简体   繁体   English

如何使用json请求发送ID?

[英]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} . 我的项目中有两件事,首先是登录页面,该页面扩展了Activity并检查用户名和密码,我正在使用以下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"}]} . 现在第二件事是我正在使用带有Activity扩展的导航抽屉,它使用不同的Fragment文件,现在在用户成功登录后,将显示第一个片段,我要在列表视图中解析一些数据,为此,我正在使用以下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. 因此,问题在于我需要使用用户登录ID 2650来解析“列表”视图中的数据,并希望通过请求将其发送到我的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 对于片段类,请检查此https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment

You can send the LOGIN_ID value from Activity as: 您可以通过以下方式从“活动”发送LOGIN_ID值:

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: 并在Fragment中通过onCreateView方法获取值:

@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. 您不需要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)); 您也可以在其中添加ID 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();
                 }
    }}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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