2

i can not fetch data from mysql database. i maked an android app which connect to mysql db and fetch data using php script.... when i run code it throws exception string cannot convert to jsonarray.... Also guide me where i put my php script in XAMP PHP script:

$con = mysql_connect("localhost","root","");
 if (!$con)
 {
   die('Could not connect: ' . mysql_error());
 }
 mysql_select_db("login",$con);
 $sql=mysql_query("SELECT * FROM category ORDER BY `category`.`category` ASC");
 while($row=mysql_fetch_assoc($sql))
 $output[]=$row;
  print(json_encode($output));
  mysql_close($con);

Code:-

tv=(TextView)findViewById(R.id.textView1);
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList nameValuePairs = new ArrayList();
    List r = new ArrayList();
    try{
    //http post
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://ip../xampp/htdocs/db.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch(Exception e){
    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //Convert response to string
    try
    {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
    sb.append(line +"\n");
    }
    is.close();
    result = sb.toString();
    }
    catch(Exception e)
    {
    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //END Convert response to string
    try{
    JSONArray jArray = new JSONArray(result);
    JSONObject json_data=null;
    for(int i=0;i<jArray.length();i++) {
    json_data = jArray.getJSONObject(i);
    tv.append(json_data.getString("category").toString()+"\n");
    }

    }
    catch(JSONException e1){
    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    } catch (ParseException e1) {
    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    }

1 Answer 1

1

The method to fetch value from mysql through php to android is as below:

Suppose you have a login Activity

User enter Username and Password. now catch both value and send to php script. the android code for it is as below:

btnlogin.setOnClickListener(new View.OnClickListener()
        {
                public void onClick(View v)
            {   

                        uname=username.getText().toString();
                        upass=password.getText().toString();
                        HttpClient client = new DefaultHttpClient();

                        tem="http://10.0.2.2:80/verify-login.php?username="+uname+"&password="+upass;
                        HttpGet request = new HttpGet(tem);
                        try
                        {
                            HttpResponse response=client.execute(request);
                            HttpEntity entity=response.getEntity();
                            InputStream is=entity.getContent();
                            InputStreamReader isr = new InputStreamReader(is);
                            BufferedReader reader = new BufferedReader(isr);
                            result=reader.readLine();   
                        } 

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

                        if(result.equals("0")==true)
                        {
                            Toast.makeText(getApplicationContext(), "Sorry try again", 1500).show();

                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "Welcome Client", 1500).show();
                            myIntent=new Intent(login_page.this,Welcome_page.class);

                        }
                    }

        });

At the php script side. the code to fetch value from database and return to android is as below:

<?php

    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("login") or die(mysql_error());

    $username=$_REQUEST['username'];
    $password=$_REQUEST['password'];
    $SelectQuery="select * from EmpLogin where C_Username='$username' and C_Password='$password'";
    $result=mysql_query($SelectQuery) or die(mysql_error());

    $count=mysql_num_rows($result);
    $row=mysql_fetch_array($result);
    if($count==0)
        echo "0";
    else
        echo $row['c_id'];
?>

This way you can fetch the value from DB and send back to android. hope this helps you. If you have any doubt then do ask me anytime.

Sign up to request clarification or add additional context in comments.

4 Comments

plz can you tell me about url which you place inside httppost and tell me where i put php script in XAMP server???
it is quite simple. the url is passed in the HttpGet and not HttpPost the code is as below: tem="http://10.0.2.2:80/verify-login.php?username="+uname+"&password="+upass; HttpGet request = new HttpGet(tem); And you will have to put the php script in your C:\XAMP\WWW folder. here verify-login.php is your php script. and 80 is the port number. you will have to change it according to your requirements.
Thanks for helping me Ankxx13 it works....:). directory path is not correct which you told me for XAMP plz correct it. This is the correct path c:\xamp\htdocs\filename.php... other things work perfectly Thanks again
@amir_ikram805 ok... the path i gave works for wamp and not for xamp.. and if mine is the correct answer. then please select my answer as the accepted answer of yours by ticking the tick mark.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.