[TUTORIAL] Connecting to MySQL database

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

Re: [TUTORIAL] Connecting to MySQL database

Postby shakey » Sat May 28, 2011 3:58 am

Hey Anybody

Please help me. I like many others have not gotten this to work, I will post my code tell me what I am doing wrong. I should mention that I am not using a local server. I have my php script on a webserver hosted by Host Gator. My DB is there also, although don't know where in the file directory it is housed. my code is below.

The Android Java File
Code: Select all
package com.connector;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


public class whitehead extends Activity {
/** Called when the activity is first created. */
   
   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources
    // but since its an example saves declaring them in the XML.
    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    txt = new TextView(getApplicationContext());
    rootLayout.addView(txt);
    setContentView(rootLayout);

    // Set the text and call the connect function.
    txt.setText("Connecting...");
  //call the method to run the data retreival
    txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://www.xtremeware.net/StreetCred/test.php"; //i use my real ip here



private String getServerData(String returnString) {
   
   InputStream is = null;
   
   String result = "";
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year","1970"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            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());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear")
                    );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);
            }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return returnString;
}   
   
}


The Php Script
Code: Select all
<?php
   mysql_connect("localhost:3306", "I put my user name here created by cpanel", "password given by cpanel")or die(mysql_error());
   echo  "Connected to MySQL<br>";
   mysql_select_db("shakey_PeopleData");
   echo "Connected to Database<br>";
   
   $q = mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
   while($e=mysql_fetch_assoc($q))
      $output[] = $e;
   print(json_encode($output));
   mysql_close();
?>


Should I be using localhost:3306 or the full path which is http://www.xtremeware.net/StreetCred/test.php.


Here is my manifest file
Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.connector"
      android:versionCode="1"
      android:versionName="1.0">
   <uses-sdk android:minSdkVersion="8" />
   

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".whitehead"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>


this is what I am getting in the LogCat
Code: Select all
05-27 22:01:11.698: ERROR/log_tag(15723): Error parsing data org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONArray



Please once I get this and figure it out I should be on my way, hopefully
shakey
Freshman
Freshman
 
Posts: 9
Joined: Sat Oct 02, 2010 1:33 pm

Top

Re: [TUTORIAL] Connecting to MySQL database

Postby krilov » Sun May 29, 2011 10:36 pm

Hi all and hell, what a great tutorial..too bad it doesn't work for me...doh....i keep seing just the URL once the emulator starts.

From reading here and there i've tried many "solutions" that worked for others...but still no results for me.

1st of all, i've modified the public static final String KEY_121 in something like http://10.0.2.2/dbAndroid/getAllPeopleBornAfter.php but nothing...

Then i just thought of using 198.162.1.x but still nothing; Then, i tried to specify the port 80 too..and still nothing.
I've deleted the min sdk android ver from the manifest.xml as someone suggested...but ..nothing

I tried creating a new AVD too but still the same results.

Moreover, right before executing this example...i tested the connection with MSQL ...using a random php file placed in the same directory of the getALLPeoplebornafter.php file..so i checked MSQL, DB_name, user, pswd and they were right.

Tbh..dunno what to do doh....any help..would be more than welcome..really.
Ty 4 your time guys
krilov
Freshman
Freshman
 
Posts: 2
Joined: Sun May 29, 2011 9:45 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby harata » Mon May 30, 2011 2:26 pm

Hi all,

Not quite sure I'm following your problem krilov, might need some more details about the issue.

I'm also having a fatal error, if I leave the code the way it is, I get a php error when viewing in a browser:

Undefined Index: year

This also stops the JSON array from being parsed correctly in android; however, strangely, it still seems to print off the json array correctly below this error in the browser.

Is there some type of server setup I'm missing or has anyone ran into this error before?
harata
Once Poster
Once Poster
 
Posts: 1
Joined: Mon May 30, 2011 2:18 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby krilov » Tue May 31, 2011 2:02 pm

krilov wrote:Hi all and hell, what a great tutorial..too bad it doesn't work for me...doh....i keep seing just the URL once the emulator starts.

From reading here and there i've tried many "solutions" that worked for others...but still no results for me.

1st of all, i've modified the public static final String KEY_121 in something like http://10.0.2.2/dbAndroid/getAllPeopleBornAfter.php but nothing...

Then i just thought of using 198.162.1.x but still nothing; Then, i tried to specify the port 80 too..and still nothing.
I've deleted the min sdk android ver from the manifest.xml as someone suggested...but ..nothing

I tried creating a new AVD too but still the same results.

Moreover, right before executing this example...i tested the connection with MSQL ...using a random php file placed in the same directory of the getALLPeoplebornafter.php file..so i checked MSQL, DB_name, user, pswd and they were right.

Tbh..dunno what to do doh....any help..would be more than welcome..really.
Ty 4 your time guys



I've been looking around for days and i did lots of local tests and still nothing...so i thought of trying it online, i mean...using a fresh created website (with MYSQL & Co. supported) and so....changing the key121 string like this: http://test.zxq.net/dbAndroid/getAllPeopleBornAfter.php

Just to be sure that both mysql settings and the php file worked rightly as well as its output, at the beginning i setted manually the condition" > 1970 " and it worked.
The output showed the right results.
So, then i modified again the php file ( the same as here in the example ) and i modified the strin key121 inside the java file.
" OFC "...once the emulator starts i see AGAIN just the url http://test.zxq.net/dbAndroid/getAllPeopleBornAfter.php -_-

Dunno if it can help you but i'm using this version of Eclipse: eclipse-java-helios-SR2-win32
And the avd i created is ver 2.2

just 1 word HELP!
krilov
Freshman
Freshman
 
Posts: 2
Joined: Sun May 29, 2011 9:45 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby Andre85 » Tue May 31, 2011 6:59 pm

Does anyone knows how can I fill a ListView pulling data from a php script hosted on a server? I can't find anything surfin' the web. Please. :?
Andre85
Freshman
Freshman
 
Posts: 8
Joined: Tue May 31, 2011 10:52 am

Re: [TUTORIAL] Connecting to MySQL database

Postby ferguior » Sat Jun 11, 2011 6:45 pm

Hi everyone!

As many of you, I got it running and it just shows the url. I've tried the different solutions proposed, like creating a new avd, etc. But nothing worked.

The logcat says there's a JSON parsing error:

Code: Select all
D/AndroidRuntime(  313): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  313): CheckJNI is ON
D/AndroidRuntime(  313): --- registering native functions ---
I/ActivityManager(   58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidconn/.AndroidConnection }
D/AndroidRuntime(  313): Shutting down VM
D/dalvikvm(  313): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  313): NOTE: attach of thread 'Binder Thread #3' failed
E/log_tag (  281): Error parsing data org.json.JSONException: Value yes of type java.lang.String cannot be converted to JSONArray
I/ActivityManager(   58): Displayed activity com.example.androidconn/.AndroidConnection: 1636 ms (total 1636 ms)


I copied exactly the same code as the tutorial so a JSON parsing error doesn't make much sense, does it?

I would really appreciate if someone who had the same problem or just knows what's wrong posts the solution to it!
ferguior
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Jun 08, 2011 7:51 pm

Top

Re: [TUTORIAL] Connecting to MySQL database

Postby christusvalerian » Sat Jun 18, 2011 8:06 am

I tried this coding it really works.Thank UUUUU
christusvalerian
Developer
Developer
 
Posts: 28
Joined: Sat Jun 18, 2011 8:03 am

Re: [TUTORIAL] Connecting to MySQL database

Postby uxc.wilis » Mon Jun 20, 2011 1:55 pm

good references,,


thx bro.

uxc.wilis
uxc.wilis
Freshman
Freshman
 
Posts: 6
Joined: Thu Dec 30, 2010 3:22 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby mattcmf » Tue Jun 21, 2011 3:32 am

Hey guys, pretty much same post as everyone else here. Just getting the URL. I think I may share some confusion with a lot of people.
There are a few main inputs

public static final String KEY_121 = "***********
IP = 31.***.***.***
Server name serverr96webhost.com
FTP user name helloworld
FTP password password
File system path /home/helloworld

I' definitely all of the other code correct and I am using a live version of the PHP file instead of hosting it locally.
Yet I just get the errors in the log cat

"Error in http connection java.net SocketException: Permission denied"
"Error converting result.java.lang.NullPointerException"
"Error parsing data org.json.JSONEException:end of input at character 0 of"

Any help would be really appreciated.
mattcmf
Freshman
Freshman
 
Posts: 2
Joined: Tue Jun 21, 2011 3:24 am

Re: [TUTORIAL] Connecting to MySQL database

Postby mattcmf » Tue Jun 21, 2011 1:50 pm

@@@@@@ [SOLVED] @@@@@@

Ok what I was doing wrong, (firstly I had the permissions in the wrong part of the manifest. It should be outside the application bracket).
Then the username I had wrong. In Cpanel instead of going to overview and using that usename. At the bottom there is a button called "Manage My SQL Databases". That has the correct MySQL Databas, MySQL User and MySQL Host.
Finally (although this may seem obvious) the log in is for the database, not the general log in. I was also using an online hosted PHP file because its just years easier. Hope this helps people.
mattcmf
Freshman
Freshman
 
Posts: 2
Joined: Tue Jun 21, 2011 3:24 am

Re: [TUTORIAL] Connecting to MySQL database

Postby uxc.wilis » Wed Jun 22, 2011 6:41 pm

goog references...

thx bro..
uxc.wilis
Freshman
Freshman
 
Posts: 6
Joined: Thu Dec 30, 2010 3:22 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby Sh466y » Fri Jul 15, 2011 12:23 am

Hello boys.

I've have the same problem as schofeild. The error of JSONArray parsing is killing me. Please help.
The error is : Value <br of type Java.lang.String cannot be converted to JSONArray.
Sh466y
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Jul 15, 2011 12:18 am

Re: [TUTORIAL] Connecting to MySQL database

Postby legi0nare » Thu Aug 18, 2011 11:34 am

Same problem here, Tried in both Online and local nothing happened. :(

Need some more advice on this.
Thanks in advance.
legi0nare
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Aug 18, 2011 11:01 am

Re: [TUTORIAL] Connecting to MySQL database

Postby schofeild » Sat Sep 03, 2011 8:53 am

guys do one thing try running the same program on different machine....it might work...it worked for me !!
schofeild
Developer
Developer
 
Posts: 40
Joined: Wed Jul 21, 2010 12:08 pm

Re: [TUTORIAL] Connecting to MySQL database

Postby sohaibrahman » Tue Sep 06, 2011 9:14 am

I am not getting it worked. I am getting the following error:
09-06 13:28:02.243: INFO/log_tag(3231): Result...<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD>
09-06 13:28:02.243: INFO/log_tag(3231): <BODY BGCOLOR="#cc9999"><H4>404 Not Found</H4>
09-06 13:28:02.243: INFO/log_tag(3231): File not found.
09-06 13:28:02.243: INFO/log_tag(3231): </BODY></HTML>
09-06 13:28:02.243: INFO/log_tag(3231): Parsing JSON data
09-06 13:28:02.264: ERROR/log_tag(3231): Error parsing data org.json.JSONException: Value <HTML><HEAD><TITLE>404 of type java.lang.String cannot be converted to JSONArray
sohaibrahman
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Sep 06, 2011 7:15 am

Top
PreviousNext

Return to Networking & Database Problems

Who is online

Users browsing this forum: No registered users and 7 guests