how to display graph in android using MySQL database

I can't get data from MySQL database for graphics. I found an example code for create graph but I want to put x axis data and y axis data from database

My example codes are:

public class Graph extends Activity {

    private XYPlot xyPlot;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.graph);

        // initialize our XYPlot reference:
        xyPlot = (XYPlot) findViewById(R.id.xyplot);

        Number[] income =  {2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 };
        Number[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 };

        final String[] mMonths = new String[] {
            "Jan","Feb", "Mar","Apr", "May","Jun",
            "Jul", "Aug","Sep","Oct", "Nov","Dec"

        };

        // Converting the above income array into XYSeries
        XYSeries incomeSeries = new SimpleXYSeries(
            Arrays.asList(income),                   // array => list
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY , // Y_VALS_ONLY means use the element index as the x value
            "Income");                                  // Title of this series

        // Converting the above expense array into XYSeries
        XYSeries expenseSeries = new SimpleXYSeries(
            Arrays.asList(expense),                 // array => list
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value
            "Expense");                                // Title of this series

        // Create a formatter to format Line and Point of income series
        LineAndPointFormatter incomeFormat = new LineAndPointFormatter(
            Color.rgb(0, 0, 255),                   // line color
            Color.rgb(200, 200, 200),               // point color
            null );                                    // fill color (none)

        // Create a formatter to format Line and Point of expense series
        LineAndPointFormatter expenseFormat = new LineAndPointFormatter(
            Color.rgb(255, 0, 0),                   // line color
            Color.rgb(200, 200, 200),               // point color
            null);                                    // fill color (none)

        // add expense series to the xyplot:
        xyPlot.addSeries(expenseSeries,expenseFormat);

        // add income series to the xyplot:
        xyPlot.addSeries(incomeSeries, incomeFormat);

        // Formatting the Domain Values ( X-Axis )
        xyPlot.setDomainValueFormat(new Format() {

            @Override
            public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
                return new StringBuffer( mMonths[ ( (Number)obj).intValue() ]  );
            }

            @Override
            public Object parseObject(String source, ParsePosition pos) {
                return null;
            }
        });

        xyPlot.setDomainLabel("");
        xyPlot.setRangeLabel("Amount in Dollars");

        // Increment X-Axis by 1 value
        xyPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);

        xyPlot.getGraphWidget().setRangeLabelWidth(50);

        // Reduce the number of range labels
        xyPlot.setTicksPerRangeLabel(2);

        // Reduce the number of domain labels
        xyPlot.setTicksPerDomainLabel(2);

        // Remove all the developer guides from the chart
        xyPlot.disableAllMarkup();
    }

Get Database Codes:

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://10.0.2.2/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_DEGERLER = "degerler";
    private static final String TAG_SICAKLIK = "Sicaklik";
    private static final String TAG_GERILIM = "Gerilim";
    private static final String TAG_AKIM = "Akim";
    private static final String TAG_REEL = "Reel Guc";
    private static final String TAG_REAKTIF = "Reaktif Guc";

    // 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>>();
     // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON response
        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_DEGERLER);

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

                    // Storing each json item in variable
                    String sicaklik = c.getString(TAG_SICAKLIK);
                    String gerilim = c.getString(TAG_GERILIM);
                    String akim = c.getString(TAG_AKIM);
                    String reel = c.getString(TAG_REEL);
                    String reaktif = c.getString(TAG_REAKTIF);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_SICAKLIK, sicaklik);
                    map.put(TAG_GERILIM, gerilim);
                    map.put(TAG_AKIM, akim);
                    map.put(TAG_REEL, reel);
                    map.put(TAG_REAKTIF, reaktif);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {

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

        ListAdapter adapter = new SimpleAdapter(
                AllProductsActivity.this, productsList,
                R.layout.list_item, new String[] { TAG_SICAKLIK,
                        TAG_GERILIM,TAG_AKIM,TAG_REEL,TAG_REAKTIF},
                new int[] { R.id.sicaklik, R.id.gerilim, R.id.akim, R.id.reel, R.id.reaktif});
        // updating listview
        setListAdapter(adapter);



    }


}

JSON Parser Codes:

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                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();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

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

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

        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();
            json = sb.toString();
        } 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());
        }

        // return JSON String
        return jObj;

    }
}

Answers


Yeah, this just isn't going to work. Activity.onCreate is not main(). You can't just put your application there.

I'm sure this isn't what you want to hear, by you really need to go all the way back to the drawing board. You are going to want to put the code that requests the JSON object into a Service.

The code that does the actual graphing looks pretty good. You will need to set it up so that when the Service succeeds in retrieving the JSON, and then parsing it, it notifies the Activity that there is something to graph.

Step back from the code and brush up on Android architecture for a couple days. It isn't hard, but it is different.


Yes.It will be possible. you can follow my example

Bar Chart in Android With out any Built in jars. Here you can get data from database and try to set the results in the arrays(Say grossSal,netSal,datelabel arrays)

Here is the simple logic with no jars needed. you can implement bar charts with your own coding from this example


Need Your Help

MySQL query which has multiple subqueries, each with different join types

php mysql subquery left-join inner-join

Let me start by giving you a diagram of the relationships between the tables used in my mysql query:

Rails not including require_tree for javascript

javascript ruby-on-rails ruby coffeescript

I have been trying for many hours to execute a simple console and alert message in javascript in my rails application, after check that more complex javascript (coffee) code does not work. The only...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.