Dear All,

I am getting the below error when i try to connect to MySQL database. I am 
using PHP for connecting to the databse stuff.

Here is my code. If i change the AVD from 4.0.3 to 2.2 then it runs fine 
and interacts with the DB. But when i run the same on AVD 4.0.3 then it 
crashes.

package com.example.androidhive;

import com.example.androidhive.library.JSONParser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 

public class AllOrderActivity extends ListActivity {
int userId;
String EmpName;
TextView tv;
    // 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_order = 
"http://localhost/android_login_api/get_all_products.php";;
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_ORDERS = "orders";
    private static final String TAG_OID = "oid";
    private static final String TAG_ORDER_DESCRIPTION = "order_description";
    private static final String TAG_EMP_NAME = "empName";
 
    // products JSONArray
    JSONArray products = null;
 
    @SuppressLint("UseValueOf")
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_order);
        Log.d("In all oder","In all order");
 
Bundle extras = getIntent().getExtras();
if (extras != null) {
userId = extras.getInt("UserId");
EmpName = extras.getString("EmpName");
}
userId = 4;
EmpName = "testing";
String s = new Integer(userId).toString();
Log.d("userId", s);
Log.d("user name", EmpName);
 tv = (TextView) findViewById(R.id.empName);

         tv.setText(EmpName); 
             
        // 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() {
 
           
            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();
                Log.d("pid in ALL",pid);
                String usrId = new Integer(userId).toString();
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditOrderActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_OID, pid);
                in.putExtra("oId", pid);
                in.putExtra("userId", usrId);
                in.putExtra("EmpName", EmpName);
 
                // 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, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllOrderActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
        Log.d("1","####");
        final String url_all_order1 = 
"http://localhost/android_login_api/get_all_products.php?uid="+userId;
        Log.d("2",url_all_order1);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
           
          //  params.add(new BasicNameValuePair("username","abcd"));  
            // getting JSON string from URL
           JSONObject json = jParser.getJSONFromUrl(url_all_order1, params);
           
            
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
 
            try {
            
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_ORDERS);
                  
                   
                    // 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_OID);
                        String name = c.getString(TAG_ORDER_DESCRIPTION);
 
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, 
String>();
 
                        // adding each child node to HashMap key => value
                        map.put(TAG_OID, id);
                        map.put(TAG_ORDER_DESCRIPTION, name);
 
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            DashboardActivity.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(
                            AllOrderActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_OID,
                            TAG_ORDER_DESCRIPTION},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
 
        }
 
    }
}

JSON parse class:

package com.example.androidhive.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

// Making HTTP request
try {
// defaultHttpClient
Log.d("URL in JSON class",url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("1", "I am here");
try {
*Log.d("2", "I am here out");// till here i am able to watch in the LogCat 
after this app crashes.*
BufferedReader readero = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sbo = new StringBuilder();
String line = null;
while ((line = readero.readLine()) != null) {
sbo.append(line + "\n");
Log.d("str", sbo.toString());
}
is.close();
json = sbo.toString();
Log.d("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

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

}

// return JSON String
return jObj;

}
}



-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to