如何用json请求发送id?

时间:2014-11-10 04:10:44

标签: android json

我的项目中有两件事情首先是登录页面,该页面使用Activity进行扩展,并检查我在json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}后面使用的用户名和密码。
现在第二件事是我使用导航抽屉,它使用Activity扩展,它使用不同的Fragment文件,现在用户登录成功后,第一个片段将显示我要在List视图中解析一些数据,为此我正在使用以下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

4 个答案:

答案 0 :(得分:1)

您可以将Activity中的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;
 }

答案 1 :(得分:0)

你不需要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));

询问服务器开发人员的请求格式,他会告诉你他正在服务器上解析的确切格式。

答案 2 :(得分:0)

更改代码,

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

答案 3 :(得分:0)

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

}