Fetch data from database to android list view - android

Im creating an android app where in im going to fetch datas such as image and text from mysql database. I have a problem with it. When i run the program, nothing was display in my listview.
Here's my City.java
public class City extends ActionBarActivity {
String myJSON;
ImageView image;
TextView name,id,description;
private static final String TAG_RESULTS="result";
public static final String TAG_ID = "place_id";
public static final String TAG_NAME = "place_name";
public static final String TAG_ADD ="description";
//public static final String TAG_PIC ="place_icture";
JSONArray cities = null;
ArrayList<HashMap<String, String>> CitiesList;
UserLocalStore userLocalStore;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.citylayout);
userLocalStore = new UserLocalStore(this);
name=(TextView)findViewById(R.id.name);
id=(TextView)findViewById(R.id.id);
description=(TextView)findViewById(R.id.description);
list = (ListView) findViewById(R.id.listView1);
CitiesList = new ArrayList<HashMap<String, String>>();
image = (ImageView)findViewById(R.id.image);
getData();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(City.this, "Opening", Toast.LENGTH_LONG).show();
Map<String, Object> map = (Map<String, Object>)parent.getItemAtPosition(position);
String info1 = (String) map.get("place_id");
String info2 = (String) map.get("place_name");
String info3 = (String) map.get("description");
//String info4 = (String) map.get("place_picture");
Intent myIntent = new Intent(view.getContext(), Login.class);
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
myIntent.putExtra("info3", info3);
//myIntent.putExtra("info4", info4);
startActivity(myIntent);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
cities = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<cities.length();i++){
JSONObject c = cities.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
//String picture = c.getString(TAG_PIC);
HashMap<String,String> persons = new HashMap<String, String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
//persons.put(TAG_PIC,picture);
CitiesList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
City.this, CitiesList, R.layout.city,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id,R.id.name, R.id.description}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/city_info.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Please change:
public static final String TAG_PIC ="place_icture";
to
public static final String TAG_PIC ="place_picture";
in the declaration.
and
persons.put(TAG_PIC,picture);
to
persons.put(TAG_PIC,String.valueOf(d));
in showList()
Hope this helps!

Related

Vertical Progress Bar on Android

I want to implement progress bar on list view for data that am getting from Mysql server here is my code any new suggestion are welcome for an example change your layout or anything which will make implementation easy as am neophyte
public class teststatusActivity extends BaseActivity {
String myJSON = "" ;
private static final String TAG_RESULTS = "result";
private static final String TAG_TICKET = "ticket_id";
private static final String TAG_Status = "ticket_status";
private static final String TAG_Status1 = "ticket_status1";
private static final String TAG_Status2 = "ticket_status2";
private static final String TAG_Status3 = "ticket_status3";
private static final String TAG_I = "";
public static final String DATA_URL = "http://103.3.62.23/complain_dashboard/api/getTicketStatus.php?ticket_id=";
public String ticketID;
JSONArray peoples = null;
ListView list;
ArrayList<HashMap<String, String>> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teststatus);
list = (ListView) findViewById(R.id.listView);
usersList = new ArrayList<HashMap<String, String>>();
getData();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONObject pe = jsonObj.getJSONObject(TAG_RESULTS);
String id = pe.getString("ticket_id");
String status = pe.getString("ticket_status");
String stat = null;
String stat1 = null;
String stat2 = null;
String stat3 = null;
if (pe.get("ticket_status").equals("0")) {
stat = "Feedback Sent To Team";
}
if (pe.get("ticket_status").equals("1")) {
stat1 = "Technical Team is Working on it";
}
if (pe.get("ticket_status").equals("2")) {
stat2 = "Your Report is About To Resolve";
}
if (pe.get("ticket_status").equals("3")) {
stat3 = "Resolved";
}
HashMap<String, String> users = new HashMap<String, String>();
users.put( TAG_TICKET , id );
users.put(TAG_Status, stat );
users.put(TAG_Status1, stat1 );
users.put(TAG_Status2, stat2);
users.put(TAG_Status3, stat3);
usersList.add(users);
ListAdapter adapter = new SimpleAdapter(
teststatusActivity.this, usersList, R.layout.list_item,
new String[]{TAG_TICKET, TAG_Status,TAG_Status1, TAG_Status2, TAG_Status3 },
new int[]{R.id.feed, R.id.feedS, R.id.feedwork, R.id.abouttoresolve, R.id.resolved}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
SharedPreferences sharedPref = getSharedPreferences("tcktid", Context.MODE_WORLD_READABLE);
final String ticket =sharedPref.getString("tid", null);
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(DATA_URL + ticket);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
} ;

Button click action not working in android listview

I am developing an android app which functions like as follows
Admin creates the data and saves it into database then user access the same data through app when it comes down to showing the data to user i fetch the data from the database which admin has already saved i show the data in listview, and listview having buttons in each row when user click on button it dose not goes to next activity.When user will click on button in listview the activity should pass to next activity.How do i do this?
//java activity
public class MainActivity extends ActionBarActivity {
String myJSON;
SimpleAdapter adapter;
Button btn;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "sname";
private static final String TAG_PRICE = "sprice";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
// ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>();
ListView list, listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView_search);
btn = (Button) findViewById(R.id.button3_book);
personList = new ArrayList<HashMap<String, String>>();
getData();
// Listview on item click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent zoom=new Intent(parent.getContext(), Details.class);
parent.getContext().startActivity(zoom);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String sname = c.getString(TAG_NAME);
String sprice = c.getString(TAG_PRICE);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,sname);
persons.put(TAG_PRICE,sprice);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.search_item,
new String[]{TAG_NAME,TAG_PRICE},
new int[]{ R.id.textView8_sellernm, R.id.textView19_bprice}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(MainActivity.this,Details.class);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://example.com/User/reg/listview.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}

How to use Fragment in Android?

iam using menu slidding, this code for call other class
}else if (id == R.id.list) {
//Set the fragment initially
StockProduct fragment = new StockProduct();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
but fragment error i don't know why...
and this is my class code
public class StockProduct extends Fragment implements ListView.OnItemClickListener {
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "name_product";
private static final String TAG_ID = "product_id";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.list_product, container, false);
list = (ListView) view.findViewById(R.id.allproduct);
personList = new ArrayList<HashMap<String, String>>();
getData();
return view;
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(Config.ALLPRODUCT_URL);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID, id);
persons.put(TAG_NAME, name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
StockProduct.this.getActivity(), personList, R.layout.list_product_component,
new String[]{TAG_ID,TAG_NAME},
new int[]{R.id.idproduct, R.id.nameproduct}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this.getActivity(), StockProductView.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String product_id = map.get(TAG_ID).toString();
intent.putExtra(Config.TAG_PRODUCT_ID,product_id);
startActivity(intent);
}}
and this is log error
Try replacing this line,
StockProduct fragment = new StockProduct();
with
Fragment fragment = new StockProduct();
Make sure all your import statements import support fragment

Android select query JSON endless cycle every 10 seconds [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Good morning, and greetings to all, I am new to android JAVA, and searching the Internet, I found a class for java android to query a database in mysql through JSON and PHP, now I'm trying,It is to consult in an endless cycle every 10 seconds.
Searching the internet, comment the following code, but do not know how to implement it ...
Any help, comments, be well appreciated, Greetings
This is the code of the class:
public class VerA extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "nombre";
private static final String TAG_ADD ="telefono";
private Handler mHandler;
private int mInterval = 8000; // 5 seconds by default, can be changed later
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
mHandler = new Handler();
startRepeatingTask();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
VerA.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://tuescuelanoticias.x10.mx/selectAllJSON.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
///course method, which should refresh the query on the base dedatos every 8 seconds
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
getData();
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
}
update code:
public class VerA extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "nombre";
private static final String TAG_ADD ="telefono";
Handler handler = new Handler();
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
handler.postDelayed(runnable, 8000);
}
// METODO QUE MUESTRA LA LISTA O LA MATRIZ
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
VerA.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
///METODO QUE EXTRAE LOS DATOS DE EL JASON PHP
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://tuescuelanoticias.x10.mx/selectAllJSON.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
///LOS METODOS SIGUIENTES MUESTRAN LA OPCION DE MENU Y CONFIGRUACIO
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
///DISQUE PARA QUE SE REFRESQUE CADA 8 SEGUNDOS, AL PARECER SI TRAE LOS DATOS PERO NO LOS DIBUJA
private Runnable runnable = new Runnable() {
public void run() {
showList();
// Do some updates
handler.postDelayed(this, 8000);
}
};
}
or how can I implement AnsyTask in my code
Basically you are looking for service that will check your database for every 10 seconds. And if there is a new data then it will fetch that data. For this you can use a service Create a class that extends Service class override onstartCommand() method and inside this method write your network request code don't forget to user threading otherwise service will take more time. If you want to create a non destroy-able service that will not be killed if you restarts your mobile then you should return Service.START_STICKY.
AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),100000, pendingIntent);
By this way you can make a network call for each 10 seconds interval . But executing service in seconds is not a good practice because it will drain your battery.

I wouldn't able to run the app in android studio emulator and even in my phone as running devices. the database Program is unfortunately stopped

public class MainActivity extends ActionBarActivity
{
String myJSON;
pri`enter code here`vate static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData(); }
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = null;
try {
httppost = new HttpPost("http://127.0.0.1/database.php");
} catch (Exception e)
{
e.getMessage();
}
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e)
{
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','person_db');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from Persons";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_row($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'address'=>$row[2]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
connect same WIFI network on both device

Categories

Resources