Domanda

After reading some tutorials i can take a list of orders from MySql database with php and show in my Android app. I need to have this list filtered by userId (the useid is saved in preferences). I have to send http request with parameter "userId" but i dont know how. The code that i have now :

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url){
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

  //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

    try{

        jArray = new JSONObject(result);            
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}    
}

For orders list:

public class Masuratori extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


    JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php");

    try{

        JSONArray  earthquakes = json.getJSONArray("earthquakes");

        for(int i=0;i<earthquakes.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = earthquakes.getJSONObject(i);

            map.put("id",  String.valueOf(i));
            map.put("name", e.getString("clie"));
            map.put("magnitude",  e.getString("userid"));
            map.put("adresa",  e.getString("adr"));
            map.put("detalii",  e.getString("det"));
            mylist.add(map);            
        }       
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_masuratori, 
                    new String[] { "name", "adresa","detalii","magnitude"}, 
                    new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3 });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
            Toast.makeText(Masuratori.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

        }
    });
}
}

I receive the userid value from preferences:

public class Calculator extends Activity {
TextView prefEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calculator);
    prefEditText= (TextView)findViewById(R.id.textUser);        
    loadPref();
    prefEditText= (TextView)findViewById(R.id.prefEditText);
    loadPref();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.calculator, menu);
    return true;
}
@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  //super.onActivityResult(requestCode, resultCode, data);

  loadPref();
 }

 private void loadPref(){
  SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);


  String my_edittext_preference = mySharedPreferences.getString("edittext_preference", "");
     prefEditText.setText(my_edittext_preference);

 }          
}
È stato utile?

Soluzione 2

Since you are only sending only one parameter, Why don't you send it in the Query String.

String userId = getUserId();
JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php?userId=" + userId);

Then you retrive it in php

$userId = $_GET['userId']

Altri suggerimenti

Before you execute() your HttpPost, you can add parameters with the following code:

// Add userId parameter
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
nameValuePairs.add(new BasicNameValuePair("userId", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top