JSONParser Aggiornato

di il
4 risposte

JSONParser Aggiornato

Ciao a tutti sto tentando di fare una app seguendo questo tutorial vecchio http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

Ho aggiornato la Classe JASONParser cosi:
public class JSONParser {



	String charset = "UTF-8";
	HttpURLConnection conn;
	DataOutputStream wr;
	StringBuilder result;
	URL urlObj;
	JSONObject jObj = null;
	StringBuilder sbParams;
	String paramsString;

	public JSONObject makeHttpRequest(String url, String method,
									  HashMap<String, String> params) {

		sbParams = new StringBuilder();
		int i = 0;
		for (String key : params.keySet()) {
			try {
				if (i != 0){
					sbParams.append("&");
				}
				sbParams.append(key).append("=")
						.append(URLEncoder.encode(params.get(key), charset));

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			i++;
		}

		if (method.equals("POST")) {
			// request method is POST
			try {
				urlObj = new URL(url);

				conn = (HttpURLConnection) urlObj.openConnection();

				conn.setDoOutput(true);

				conn.setRequestMethod("POST");

				conn.setRequestProperty("Accept-Charset", charset);

				conn.setReadTimeout(10000);
				conn.setConnectTimeout(15000);

				conn.connect();

				paramsString = sbParams.toString();

				wr = new DataOutputStream(conn.getOutputStream());
				wr.writeBytes(paramsString);
				wr.flush();
				wr.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else if(method.equals("GET")){
			// request method is GET

			if (sbParams.length() != 0) {
				url += "?" + sbParams.toString();
			}

			try {
				urlObj = new URL(url);

				conn = (HttpURLConnection) urlObj.openConnection();

				conn.setDoOutput(false);

				conn.setRequestMethod("GET");

				conn.setRequestProperty("Accept-Charset", charset);

				conn.setConnectTimeout(15000);

				conn.connect();

			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		try {
			//Receive the response from the server
			InputStream in = new BufferedInputStream(conn.getInputStream());
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			result = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}

			Log.d("JSON Parser", "result: " + result.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}

		conn.disconnect();

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(result.toString());
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON Object
		return jObj;
	}
}
e modificato l'activity che carica tutti i dati su una listview premendo un button cosi:
public class AllProductsActivity extends ListActivity {

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> productsList;

	// url to get all products list
	private static String url_all_products = "http://192.168.3.199/RiparazioniServer/Test.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "products";
	private static final String TAG_PID = "pid";
	private static final String TAG_NAME = "name";

	// products JSONArray
	JSONArray products = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_products);

		// Hashmap for ListView
		productsList = new ArrayList<HashMap<String, String>>();

		// Loading products in Background Thread
		new LoadAllProducts().execute();

		// Get listview
		ListView lv = getListView();

		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String pid = ((TextView) view.findViewById(R.id.pid)).getText()
						.toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						EditProductActivity.class);
				// sending pid to next activity
				in.putExtra(TAG_PID, pid);
				
				// starting new activity and expecting some response back
				startActivityForResult(in, 100);
			}
		});

	}

	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received 
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}

	}

	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	class LoadAllProducts extends AsyncTask<String, String, JSONObject> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllProductsActivity.this);
			pDialog.setMessage("Loading products. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected JSONObject doInBackground(String... args) {

			try {
				// Building Parameters
			HashMap<String, String> params = new HashMap<>();
				params.put("pid", args[0]);
			//params.put("password", args[1]);
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
			
			// Check your log cat for JSON reponse
			Log.d("All Products: ", json.toString());


				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					products = json.getJSONArray(TAG_PRODUCTS);

					// looping through All Products
					for (int i = 0; i < products.length(); i++) {
						JSONObject c = products.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_PID);
						String name = c.getString(TAG_NAME);

						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_PID, id);
						map.put(TAG_NAME, name);

						// adding HashList to ArrayList
						productsList.add(map);
					}
				} else {
					// no products found
					// Launch Add New product Activity
					Intent i = new Intent(getApplicationContext(),
							NewProductActivity.class);
					// Closing all previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							AllProductsActivity.this, productsList,
							R.layout.list_item, new String[] { TAG_PID,
									TAG_NAME},
							new int[] { R.id.pid, R.id.name });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
Pero ottengo questo errore:
[ 09-15 21:40:23.104 14328:14328 D/         ]
                                                                         HostConnection::get() New Host Connection established 0xaa9e4b60, tid 14328
09-15 21:40:23.884 14328-14328/com.example.androidhive D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
09-15 21:40:23.888 14328-14328/com.example.androidhive E/WindowManager: android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{2fa730c V.E...... R.....I. 0,0-802,301} that was originally added here
                                                                            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
                                                                            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
                                                                            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                            at android.app.Dialog.show(Dialog.java:319)
                                                                            at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:115)
                                                                            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
                                                                            at android.os.AsyncTask.execute(AsyncTask.java:551)
                                                                            at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:55)
                                                                            at android.app.Activity.performCreate(Activity.java:6237)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-15 21:40:23.909 14328-14328/com.example.androidhive D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
09-15 21:42:51.531 14328-14334/com.example.androidhive W/art: Suspending all threads took: 6.070ms
09-15 21:43:19.571 14328-14334/com.example.androidhive W/art: Suspending all threads took: 5.042ms
09-15 21:45:10.752 14328-14334/com.example.androidhive W/art: Suspending all threads took: 5.774ms
09-15 21:45:22.942 14328-14393/com.example.androidhive I/Process: Sending signal. PID: 14328 SIG: 9

4 Risposte

  • Re: JSONParser Aggiornato

    Hai postato anche sull'altro forum..
  • Re: JSONParser Aggiornato

    oregon ha scritto:


    Hai postato anche sull'altro forum..
    Si su 2 ho violato qualche regola?
  • Re: JSONParser Aggiornato

    Basta leggerle le regole per saperlo prima....
  • Re: JSONParser Aggiornato

    Chiedo Scusa ma purtroppo la programmazione nei forum italiani il più delle volte non trova riscontro mi sono iscritto qui, spero di venire smentito,vi ringrazio in anticipo spero mi possiate aiutare
Devi accedere o registrarti per scrivere nel forum
4 risposte