Here we are accessing a mysql database and get the table values and show it in the Android side as tables.

These are some tutorials that I have posted on connection with php and getting tablevalues.
1. Android phpmySQL connection redone.
2. Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

Here we have 3 classes
1. GetDataFromDB.java – Gets value from DB in the form of JSON.
2. Users.java _ Class which holds the one row table object.
3. MainActivity.java _ Which implements these classes and show the tables.

MainActivity.java

package com.coderzheaven.gettablefromphp;

import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.   graphics.   Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

	String data = "";
	TableLayout tl;
	TableRow tr;
	TextView label;

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

		tl = (TableLayout) findViewById(R.id.maintable);

		final GetDataFromDB getdb = new GetDataFromDB();
		new Thread(new Runnable() {
			public void run() {
				data = getdb.getDataFromDB();
				System.out.println(data);
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						ArrayList<users> users = parseJSON(data);
						addData(users);						
					}
				});
				
			}
		}).start();
	}

	public ArrayList</users><users> parseJSON(String result) {
		ArrayList</users><users> users = new ArrayList</users><users>();
		try {
			JSONArray jArray = new JSONArray(result);
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject json_data = jArray.getJSONObject(i);
				Users user = new Users();
				user.setId(json_data.getInt("id"));
				user.setName(json_data.getString("name"));
				user.setPlace(json_data.getString("place"));
				users.add(user);
			}
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());  
		}
		return users;
	}

	void addHeader(){
		/** Create a TableRow dynamically **/
		tr = new TableRow(this);

		/** Creating a TextView to add to the row **/
		label = new TextView(this);
		label.setText("User");
		label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		label.setPadding(5, 5, 5, 5);
		label.setBackgroundColor(Color.RED);
		LinearLayout Ll = new LinearLayout(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.setMargins(5, 5, 5, 5);
		//Ll.setPadding(10, 5, 5, 5);
		Ll.addView(label,params);
		tr.addView((View)Ll); // Adding textView to tablerow.

		/** Creating Qty Button **/
		TextView place = new TextView(this);
		place.setText("Place");
		place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		place.setPadding(5, 5, 5, 5);
		place.setBackgroundColor(Color.RED);
		Ll = new LinearLayout(this);
		params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.setMargins(0, 5, 5, 5);
		//Ll.setPadding(10, 5, 5, 5);
		Ll.addView(place,params);
		tr.addView((View)Ll); // Adding textview to tablerow.

		 // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
	}
	
	@SuppressWarnings({ "rawtypes" })
	public void addData(ArrayList<Users> users) {

		addHeader();
		
		for (Iterator i = users.iterator(); i.hasNext();) {

			Users p = (Users) i.next();

			/** Create a TableRow dynamically **/
			tr = new TableRow(this);

			/** Creating a TextView to add to the row **/
			label = new TextView(this);
			label.setText(p.getName());
			label.setId(p.getId());
			label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
			label.setPadding(5, 5, 5, 5);
			label.setBackgroundColor(Color.GRAY);
			LinearLayout Ll = new LinearLayout(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.setMargins(5, 2, 2, 2);
			//Ll.setPadding(10, 5, 5, 5);
			Ll.addView(label,params);
			tr.addView((View)Ll); // Adding textView to tablerow.

			/** Creating Qty Button **/
			TextView place = new TextView(this);
			place.setText(p.getPlace());
			place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
			place.setPadding(5, 5, 5, 5);
			place.setBackgroundColor(Color.GRAY);
			Ll = new LinearLayout(this);
			params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.setMargins(0, 2, 2, 2);
			//Ll.setPadding(10, 5, 5, 5);
			Ll.addView(place,params);
			tr.addView((View)Ll); // Adding textview to tablerow.

			 // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
		}
	}
}

GetDataFromDB.java

package com.coderzheaven.gettablefromphp;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetDataFromDB {

	public String getDataFromDB() {
		try {

			HttpPost httppost;
			HttpClient httpclient;
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost(
					"http://10.0.2.2/test/GetUsers.php"); // change this to your URL.....
			ResponseHandler<string> responseHandler = new BasicResponseHandler();
			final String response = httpclient.execute(httppost,
					responseHandler);
			
			return response.trim();

		} catch (Exception e) {
			System.out.println("ERROR : " + e.getMessage());
			return "error";
		}
	}
}

Users.java

package com.coderzheaven.gettablefromphp;

public class Users {

	int id;
	String name;
	String place;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPlace() {
		return place;
	}
	public void setPlace(String place) {
		this.place = place;
	}
	
}

The activity_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <scrollview android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:    scrollbars  =  "none"
    android:layout_below="@+id/textView1">
        <tablelayout android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:stretchColumns="1,1,1"
            android:id="@+id/maintable" >
        </tablelayout>
    </scrollview>
    
</relativelayout>

The server Side php.

GetUsers.php

< ?php

	mysql_connect("localhost","root",""); // host, username, password...
	mysql_select_db("testdb"); // db name...
	 
	$q=mysql_query("SELECT * FROM users");
	while($row=mysql_fetch_assoc($q))
			$json_output[]=$row;
	 
	print(json_encode($json_output));
	 
	mysql_close();
	
?>

Table Php Android

Table Php Android

Download the complete source code from here.

Download
.

Join the Forum discussion on this post

 

49 Comments

  1. steve September 25, 2012 at 10:48 pm

    thanks for your efforts ,

    but actually it doesn’t work there is a problem says,

    error parsing data org.json.JSONException: value error of type java.lang.string cannot be converted to JSONArray

    here is the out put of GetUsers.php

    [{“id”:”1″,”name”:”lolo”,”place”:”usa”},{“id”:”2″,”name”:”tala”,”place”:”nyc”}]

    would you please help me to fix it ,,

    thanks in advance

     
    • James September 26, 2012 at 6:20 pm

      Hey Steve :- Some extra characters are coming along with your output from the PHP side, so it cannnot be parsed into JSON array.

       
      • MK January 1, 2013 at 8:42 am

        how to fix this problem? any help?

         
        • James January 1, 2013 at 2:50 pm

          what is your problem?

           
      • Laxman November 14, 2014 at 12:12 pm

        from PHP File we are getting the expected result but not in android app that we have developed with your source code. can you help me on this revert where i solve the issue and will get the result. Please this is big issue i am trying it from 2 week and not got the result. Please Help me where i can change the code to get proper output on android app running on emulator and androide device!.
        Laxman

         
        • James November 14, 2014 at 1:57 pm

          Send your code in a simplified manner to coderzheaven@gmail.com. I will try to fix it.

           
          • Laxman November 15, 2014 at 7:01 am

            Sir, i have sent you a mail with source code. Please help in this issue and send me by the revert source code or tell me where the issue in this project.

             
          • Laxman November 15, 2014 at 7:03 am

            here is the out put of GetUsers.php that you have given in this demo.

            [{“id”:”1″,”name”:”Laxman”,”place”:”India”}]

             
  2. derek November 2, 2012 at 10:43 pm

    getting this error

    The method run() of type new Runnable(){} must override a superclass method MainActivity.java /com.coderzheaven.gettablefromphp.MainActivity/src/com/coderzheaven/gettablefromphp line 45 Java Problem

     
  3. James January 23, 2013 at 12:37 pm

    hanks for your efforts ,

    but actually it doesn’t work there is a problem says,

    error parsing data org.json.JSONException: value error of type java.lang.string cannot be converted to JSONArray

    here is the out put of GetUsers.php

    [{“id”:”1″,”name”:”James”,”place”:”India”}]
    would you please help me to fix it ,,

     
  4. Kennedy Abad January 29, 2013 at 8:14 am

    hello. thanks for the tutorial, the codes works only when i run it on the emulator, it showed me the result that i expected, but every time i install the .apk file on a real android device the application doesn’t retrieve any data.

    can you please help me with this?

    i guest, it has something to do when my

    httppost = new HttpPost(
    “http://10.0.2.2/myrecords/RetrieveUsers.php”);

    i started writing android apps last month so i merely need your help…

    thanks a lot. . .

     
    • jayant February 8, 2013 at 2:52 am

      change 10.0.2.2 to your systems ip address which is got by start>cmd>ipconfig and press enter in windows.

       
    • Azahar December 13, 2013 at 7:16 pm

      Change 10.0.2.2 to external IPv4 address . cmd-ipconfig

       
  5. Kennedy Abad January 29, 2013 at 8:19 am

    can anybody out there help me with this?

    please, i am really new to android development.

    need help.

     
  6. Pingback: What are webservices? How we can use in Android?

  7. malik March 30, 2013 at 2:03 pm

    Error parsing data org.json.JSONException: Value error of type java.lang.String cannot be converted to JSONArray

     
    • James March 31, 2013 at 7:12 am

      You have some error in the JSON. Check whether you are not adding anything(such as a character or string) to the JSON String from the server. You should only pass JSON String from the server so that the JSON Parser can understand the string.

       
      • malik March 31, 2013 at 7:43 am

        I submit only string.but i run only above given code without a single change.I dont know what we do?

         
  8. fahim April 5, 2013 at 10:58 am

    thanx dear you solve my problem

     
  9. jig August 24, 2013 at 1:07 pm

    sir i want id in output what should i do??

     
    • James August 25, 2013 at 4:36 pm

      create a new tablerow and set id as text in a textview in that row.

       
  10. udhayabanu October 15, 2013 at 10:32 am

    sir,
    I have an android application wherein i extract record from mysql based on user input as listview in android. In the later stage when i click on one of the list it should direct me to another activity. While running this application in emulator i am not getting the result. Can u please help. I am trying this for past 2 weeks.

    My main activity
    package com.example.pharmacylist;

    import java.util.ArrayList;
    import java.util.HashMap;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.StrictMode;

    import com.example.pharmacylist.R;
    import com.example.pharmacylist.SinglePlace;
    import com.example.pharmacylist.JSONParser;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    //import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.AdapterView.OnItemClickListener;
    //import android.widget.Toast;
    //import android.widget.AdapterView.OnClickListener;

    //import android.view.View.OnClickListener;
    public class MainActivity extends ListActivity {
    ArrayList<HashMap> pharmacy;
    EditText byear; // To take birthyear as input from user
    Button submit;
    //TextView tv;
    ListView tv;

    // TextView to show the result of MySQL query
    JSONArray returnString; // to store the result of MySQL query after decoding JSON
    //String returnString;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application’s main thread
    .penaltyLog().build());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pharmacy = new ArrayList<HashMap>();
    byear = (EditText) findViewById(R.id.editText1);
    submit = (Button) findViewById(R.id.submitbutton);
    tv=getListView();
    tv = (ListView) findViewById(android.R.id.list);
    //tv = (TextView) findViewById(R.id.showresult);
    // define the action when user clicks on submit button
    submit.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {
    // declare parameters that are passed to PHP script i.e. the name “birthyear” and its value submitted by user
    ArrayList postParameters = new ArrayList();

    // define the parameter
    postParameters.add(new BasicNameValuePair(“search”,
    byear.getText().toString()));
    String response = null;

    // call executeHttpPost method passing necessary parameters
    try {
    response = JSONParser.executeHttpPost(
    //”http://129.107.187.135/CSE5324/jsonscript.php”, // your ip address if using localhost server
    “http://www.sablabs.com/Calendar/pharmacy1.php”, // in case of a remote server
    postParameters);

    // store the result returned by PHP script that runs MySQL query
    String result = response.toString();
    // String[] result = response;
    //parse json data
    try{

    returnString =null;
    JSONArray jArray = new JSONArray(result);
    // JSONObject jsonObj= new JSONObject(new String(result));

    // JSONArray json_data = jArray.getJSONArray(“json_data”);
    //returnString = response.getJSONArray(“pharmacy”);
    for(int i=0;i<jArray.length();i++){

    JSONObject json_data = jArray.getJSONObject(i);
    //Log.i("log_tag","search: "+json_data.getString("search")+
    // ",name: "+json_data.getString("name"));
    //Get an output to the screen

    String name = "\n"+ json_data.getString("name");

    HashMap map = new HashMap();
    //map.put(“name”,json_data.toString(“name”));
    // map.put(“name”,returnString);
    map.put(“name”,name);
    pharmacy.add(map);

    // name.append((“Name : ” +name);)
    //returnString += “\n” +json_data.getString(“name”);
    }
    }

    catch(JSONException e){
    Log.e(“log_tag”, “Error parsing data “+e.toString());
    }

    try{
    //tv.setFilterText(pharmacy);
    //ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, );
    //listView.setAdapter(adapter);
    SimpleAdapter adapter = new SimpleAdapter(
    MainActivity.this, pharmacy,
    android.R.layout.simple_list_item_1, new String[] { “returnString”},
    new int[] {android. R.id.list});

    // SimpleAdapter adapter = new SimpleAdapter(
    // MainActivity.this,android.R.layout.simple_list_item_1, R.id.list,pharmacy);
    tv.setAdapter(adapter);

    adapter.notifyDataSetChanged();

    //((TextView) tv).setText(returnString);
    //tv.setText(returnString);

    }
    catch(Exception e){
    Log.e(“log_tag”,”Error in Display!” + e.toString());;
    }
    }
    catch (Exception e) {
    Log.e(“log_tag”,”Error in http connection!!” + e.toString());
    }
    }
    });
    // tv.setAdapter(adapter);
    //tv.setOnClickListener(new View.OnClickListener(){

    tv.setOnItemClickListener(new OnItemClickListener() {

    //@Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {
    //@Override
    // public void onClick( View view) {

    // getting values from selected ListItem
    String reference = ((TextView) view.findViewById(android.R.id.list)).getText().toString();
    Bundle b = new Bundle();
    //b.putString(“result.name”, reference);
    b.putString(“tv.getItemAtPosition(position)”, reference);
    // b.putString(“result.address2”, reference);
    //b.putString(“result.address3”, reference);
    //b.putString(“result.telephone”, reference);
    // Starting new intent
    Intent in = new Intent(getApplicationContext(),
    SinglePlace.class);
    in.putExtras(b);
    // Sending place refrence id to single place activity
    // place refrence id used to get “Place full details”
    startActivity(in);
    }

    });
    }
    }

    My http request
    package com.example.pharmacylist;

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.net.URI;

    import java.util.ArrayList;

    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.HttpGet;

    import org.apache.http.client.methods.HttpPost;

    import org.apache.http.conn.params.ConnManagerParams;

    import org.apache.http.impl.client.DefaultHttpClient;

    import org.apache.http.params.HttpConnectionParams;

    import org.apache.http.params.HttpParams;

    import android.util.Log;

    public class JSONParser {

    /** The time it takes for our client to timeout */

    public static final int HTTP_TIMEOUT = 30 * 1500; // milliseconds

    /** Single instance of our HttpClient */

    private static HttpClient mHttpClient;

    /**

    * Get our single instance of our HttpClient object.

    *

    * @return an HttpClient object with connection parameters set

    */

    private static HttpClient getHttpClient() {

    if (mHttpClient == null) {

    mHttpClient = new DefaultHttpClient();

    final HttpParams params = mHttpClient.getParams();

    HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);

    HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);

    ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);

    }

    return mHttpClient;

    }

    /**

    * Performs an HTTP Post request to the specified url with the specified

    * parameters.

    *

    * @param url

    * The web address to post the request to

    * @param postParameters

    * The parameters to send via the request

    * @return The result of the request

    * @throws Exception

    */

    public static String executeHttpPost(String url,

    ArrayList postParameters) throws Exception {

    BufferedReader in = null;

    try {

    HttpClient client = getHttpClient();

    HttpPost request = new HttpPost(url);

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(

    postParameters);

    request.setEntity(formEntity);

    HttpResponse response = client.execute(request);

    in = new BufferedReader(new InputStreamReader(response.getEntity()

    .getContent()));

    StringBuffer sb = new StringBuffer(“”);

    String line = “”;

    String NL = System.getProperty(“line.separator”);

    while ((line = in.readLine()) != null) {

    sb.append(line + NL);

    }

    in.close();

    String result = sb.toString();

    return result;

    } finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException e) {

    Log.e(“log_tag”, “Error converting result “+e.toString());

    e.printStackTrace();

    }

    }

    }

    }

    /**

    * Performs an HTTP GET request to the specified url.

    *

    * @param url

    * The web address to post the request to

    * @return The result of the request

    * @throws Exception

    */

    public static String executeHttpGet(String url) throws Exception {

    BufferedReader in = null;

    try {

    HttpClient client = getHttpClient();

    HttpGet request = new HttpGet();

    request.setURI(new URI(url));

    HttpResponse response = client.execute(request);

    in = new BufferedReader(new InputStreamReader(response.getEntity()

    .getContent()));

    StringBuffer sb = new StringBuffer(“”);

    String line = “”;

    String NL = System.getProperty(“line.separator”);

    while ((line = in.readLine()) != null) {

    sb.append(line + NL);

    }

    in.close();

    String result = sb.toString();

    return result;

    } finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException e) {

    Log.e(“log_tag”, “Error converting result “+e.toString());

    e.printStackTrace();

    }

    }

    }

    }

    }

    My activity_main

    Can u please help me get the result in listview.

     
  11. sandesh October 23, 2013 at 11:30 am

    thanks for the tutorial…

     
  12. Anil October 25, 2013 at 5:59 am

    Superb…. !!!

     
  13. fa,eee December 10, 2013 at 7:25 am

    Hello.why is it that the eclipse emulator not displaying the values? table is empty even though data is inserted through mysql workbench.

     
    • James December 15, 2013 at 3:40 pm

      check whether your url is correct and it is retreiving values from the DB.

       
  14. fa,eee December 27, 2013 at 4:38 am

    hi. I have this problem , Error parsing data org.json.JSONException: No value for name
    why is this so?

     
  15. Pingback: Retrieve database value into Textview in androidCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, u

  16. john January 15, 2014 at 6:29 am

    hello! Thank you for this tutorial. I tried it and it worked! However, is it possible to display the database value in textviews and not in table format? I have a database which has a table “marketing”. The first column is “product” and the second column is “price”. I wanted to retrieve the value of product in textview1 which is above textview2. textview2 will display the table value for price. Both textviews will be at the center of the screen. Is this even possible?

     
    • James January 31, 2014 at 6:19 pm

      yes its possible. please workaround with this sample itself changing the gravity etc, you will get.

       
  17. John January 28, 2014 at 2:48 pm

    Hey this tutorial is really helpful!
    I have a question for you, How can the data were renewed within this time?
    It will help me really say one way.
    Sorry for my English.

     
  18. Ronald April 10, 2014 at 4:27 pm

    Hi! Thank you for this tutorial. There is no error in parsing data, the screen display the rows with background color gray but it’s not displaying any texts.. Sir can you please help me how to solve this problem… Thank you in advance..

     
    • James April 15, 2014 at 5:31 pm

      Change the textview textcolor to a visible color.

       
  19. james May 21, 2014 at 6:14 am

    I try too parsing session data from this code. So not all data from database printed at table.
    I use login and from login I keep session login
    ex: I want printed data with id=2,
    so at my php file

     
  20. Naresh May 24, 2014 at 7:52 am

    James

    Thanks for the tutorial. I am facing an issue here. The following exception is through from the code

    org.apache.http.NoHttpResponseException: the target server failed to respond

    I used the same code for httpConnection. Please help me out in proceeding further.

    Thanks

     
    • James June 22, 2014 at 5:40 pm

      please check whether you are connected to the internet and your server is up.

       
  21. Gwendoline Stacy May 26, 2014 at 5:49 pm

    Hi! Thanks for the tutorial.. But the code shows an error in converting java.lang.String to JSONArray. I am new to android and have no prior knowledge of the problem. Could you please explain how to solve this? Thank you..

     
    • James June 22, 2014 at 5:39 pm

      Some unidentified characters may be there in the result or some JSON format error. Please try to print out the exception and see.

       
  22. jagadeesh October 2, 2014 at 6:22 am

    Thanks for the tutorial it worked

     
  23. guccini November 30, 2014 at 5:39 pm

    how can set another font?

     
  24. Peter December 18, 2014 at 9:35 pm

    Hi,

    i changed ur code a bit:
    in the first column a checkbox will be there instead of textview. -> working
    in second column a textview with names from the DB. -> working

    My problem:
    I need the result of the checkbox and the text in the checkbox in a new array for updating my DB.
    I think I need an ID for every checkbox to fill my new array with a loop. I am right?

    I cant set an ID with the iterator, i tried so many, but nothing worked.

    Can you help to solve it?

    thx in advance


    void addHeader(){
    /** Create a TableRow dynamically **/
    tr = new TableRow(this);

    /** Creating a TextView to add to the row **/
    label = new TextView(this);
    label.setText("Inventarnummer");
    label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT));
    label.setPadding(5, 5, 5, 5);
    label.setBackgroundColor(Color.RED);
    LinearLayout Ll = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    Ll.addView(label,params);
    tr.addView((View)Ll); // Adding textView to tablerow.

    /** Creating Qty Button **/
    TextView place = new TextView(this);
    place.setText("Name");
    place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT));
    place.setPadding(5, 5, 5, 5);
    place.setBackgroundColor(Color.RED);
    Ll = new LinearLayout(this);
    params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT);
    params.setMargins(0, 5, 5, 5);
    Ll.addView(place,params);
    tr.addView((View)Ll); // Adding textview to tablerow.

    // Add the TableRow to the TableLayout
    tl.addView(tr, new TableLayout.LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
    }

    @SuppressWarnings({ "rawtypes" })
    public void addData(ArrayList users) {

    addHeader();

    for (Iterator i = users.iterator(); i.hasNext();) {
    Users p = (Users) i.next();

    /** Create a TableRow dynamically **/
    tr = new TableRow(this);
    /** Creating a TextView to add to the row **/

    //Checkbox in first column
    CheckBox cb = new CheckBox(this);
    cb.setText(p.getEan());
    Ll1.addView(cb);
    tr.addView((View)Ll1); // Adding textView to tablerow.

    /** Creating a TextView to add to the row **/
    label = new TextView(this);
    label.setText(p.getName());
    label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT));
    label.setPadding(5, 5, 5, 5);
    label.setBackgroundColor(Color.GRAY);
    LinearLayout Ll = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 2, 2, 2);
    Ll.addView(label,params);
    tr.addView((View)Ll); // Adding textView to tablerow.

    // Add the TableRow to the TableLayout
    tl.addView(tr, new TableLayout.LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
    }
    }

     
    • James December 19, 2014 at 5:47 pm

      Hi Can you please send the project at coderzheaven@gmail.com with the server from the response hardcoded in the code. So that I can fix it.

       
  25. usama December 23, 2014 at 12:09 pm

    12-23 17:03:30.453: E/log_tag(276): Error parsing data org.json.JSONException: Value error of type java.lang.String cannot be converted to JSONArray
    thanku for code brother run yor code but i will not get the table value plz help me i am trying last 2 week but i have facing a lot of problem ….i will just change the code ip address of my locahost 127.0.0.1 but this error com

     
    • James December 31, 2014 at 10:33 am

      There is something wrong with your JSON format. Please fix that.

       
  26. Mark July 13, 2015 at 5:17 pm

    How do you add more rows? I have 5 columns in my database I want to display in the app

    Thanks

     
    • James July 14, 2015 at 9:50 am

      Its already mentioned in the article. Check addData() function.

       
  27. Urvashi sondagar April 19, 2017 at 8:50 am

    hi,

    Can anyone help me to fetch the data into expandable listview from mysql

     
  28. jamshid hussain April 26, 2017 at 12:11 pm

    Sir Good tutorial .. But I am facing an error that org.json.JSONException: Value error of type java.lang.String cannot be converted to JSONArray

    this is the result

    [{“id”:”1″,”username”:”admin”,”password”:”admin”,”name”:”Admin”,”position”:”admin”},{“id”:”2″,”username”:”cashier”,”password”:”cashier”,”name”:”Cashier Pharmacy”,”position”:”Cashier”},{“id”:”3″,”username”:”admin”,”password”:”admin123″,”name”:”Administrator”,”position”:”admin”},{“id”:”4″,”username”:”admin”,”password”:”123″,”name”:”jamshid”,”position”:”admin”},{“id”:”5″,”username”:”amjad”,”password”:”1234″,”name”:”amjad hussain”,”position”:”caschier”},{“id”:”6″,”username”:”amjad”,”password”:”123″,”name”:”amjad”,”position”:”admin”}]

    []JSON
    0{}
    1{}
    2{}
    3{}
    4{}
    5{}

    Sir please help me

     
    • James April 30, 2017 at 6:54 am

      Hi Jamshid,

      There is some error in your json format. Please validate your json in this website (https://jsonformatter.curiousconcept.com/).
      Fix the errors and then parse it.

      Thanks for visiting my website.
      James.

       

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.