繁体   English   中英

如何使用json请求发送ID?

[英]How to send id with json request?

我的项目中有两件事,首先是登录页面,该页面扩展了Activity并检查用户名和密码,我正在使用以下json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}
现在第二件事是我正在使用带有Activity扩展的导航抽屉,它使用不同的Fragment文件,现在在用户成功登录后,将显示第一个片段,我要在列表视图中解析一些数据,为此,我正在使用以下json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]}
因此,问题在于我需要使用用户登录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();
                 }
    }}

}

对于片段类,请检查此https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment

您可以通过以下方式从“活动”发送LOGIN_ID值:

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

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

并在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);
}

编辑:

删除返回行,检查此代码:

 @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;
 }

您不需要NameValuePairs。 删除下面的行。

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

创建另一个对象。

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

您也可以在其中添加ID request.put("ID", ID_VALUE));

询问服务器开发人员的请求格式,他将让您知道他正在服务器上解析的确切格式。

更改代码,

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