How to insert data into MySQL Server using ArrayAdapter (Java)? - java

I am new in android development, I want to insert call log details in MySQL database, here I have created simple ArrayAdapter that's not getting set in listview and second thing is, how to insert data in MySQL server.
Here is my java code
public class MainActivity extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
getCallDetails();
}
private void getCallDetails()
{
StringBuffer sb = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,null, null, strOrder);
int number1 = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type1 = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Log :");
while (managedCursor.moveToNext())
{
final String number = managedCursor.getString(number1);
final String type2 = managedCursor.getString(type1);
final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
final String duration = managedCursor.getString(duration1);
String type = null;
final String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
switch (callcode)
{
case CallLog.Calls.OUTGOING_TYPE:
type = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
type = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
type = "Missed";
break;
}
List<DataBean> DataBeanList = new ArrayList<DataBean>();
DataBean dataBean = new DataBean(number, type, fDate, duration);
DataBeanList.add(dataBean);
Log.d("tag", DataBeanList.toString());
}
managedCursor.close();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1);
listView.setAdapter(arrayAdapter);
}
}
Here is my php script.........
<?php
//Importing our db connection script
require_once('connect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$number = $_POST['number'];
$duration = $_POST['duration'];
$type = $_POST['type'];
$time = $_POST['time'];
//Creating an sql query
$sql = "INSERT INTO call_detail (number,duration,type,time) VALUES ('$number','$duration','$type','$time')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Entry Added Successfully';
}else{
echo 'Could Not Add Entry';
}
//Closing the database
mysqli_close($con);
}

Well i am using this method to upload data from Android to MySQL Database. First of all you need an AsyncTask to communicate with the .php file and send the data. So i would suggest to try this:
public class MyInsertDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage("Data Processing");
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
setupDataToDB();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(dataToWrite.toString());
Log.e("Data To Write", dataToWrite.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.e("Response Code ", String.valueOf(responseCode));
if (responseCode == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder jsonResult = inputStreamToString(inputStream, YourActivity.this);
JSONObject jsonResponse = new JSONObject(jsonResult.toString());
Log.e("Data From JSON", jsonResponse.toString());
return true;
}else{
InputStream inputStream = new BufferedInputStream(urlConnection.getErrorStream());
Log.e("ERROR STREAM", inputStream.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (aVoid){
Toast.makeText(YourActivity.this, "Data Sent", Toast.LENGTH_LONG).show();
YourActivity.this.finish();
}else{
Toast.makeText(YourActivity.this, "There was a problemm sending the data. Please try again", Toast.LENGTH_LONG).show();
}
}
}
private void setupDataToDB() {
JSONObject dataToWrite = new JSONObject();
try {
dataToWrite.put("number", numberStringFromJava);
dataToWrite.put("duration", durationStringFromJava);
dataToWrite.put("type", typeStringFromJava);
dataToWrite.put("time", timeStringFromJava);
} catch (JSONException e) {
e.printStackTrace();
}
}
and then your InputStreamToString method:
public StringBuilder inputStreamToString(InputStream is, Activity activity) {
String rLine;
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
activity.finish();
}
return answer;
}
And this should insert the data if everything is correct. You have to execute it like this:
new MyInsertDataTask().execute("Your_php_file_path");
Hope it helps!!!

Watch these videos and learn how to insert data into online phpmyadmin server using your android app. For this, get a free web hosting server from 000webhost for creating a database online to store data and then can retrieve data online.
Simple and Interesting way to learn how to store data online on a web server.
https://www.youtube.com/watch?v=k3O3CY75ITY
This is the first part of the video.

Related

Unable to send data to server in Android

I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.
This is the error I'm facing
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6
The code goes like this...
Main Activity
public class MainActivity extends AppCompatActivity {
Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
e1 = (EditText) findViewById(R.id.editText9);
service=new HTTPURLConnection();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!e1.getText().toString().equals("") ) {
strname = e1.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(MainActivity.this, Student1.class);
startActivity(intent);
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("name", strname);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(success==1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
HTTPURLConnection
public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Log.d("Output",br.toString());
while ((line = br.readLine()) != null) {
response += line;
Log.d("output lines", line);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}}
My PHP code
add_employee.php
<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO `employee` (`emp_name`)
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>
connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>

Can't connect to php in Android Application

Now I'm working on RESTful API with php and try to connect to it from Android
But I can't connect because it's always catch IOException
here's my Android Code (OnReg is the method when clicked Register Button)
public void OnReg(View view)
{
str_email = et_email.getText().toString();
str_password = et_password.getText().toString();
str_fname = et_fname.getText().toString();
str_lname = et_lname.getText().toString();
type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_email, str_password, str_fname, str_lname);
}
Here's the BackgroundWorker class
public class BackgroundWorker extends AsyncTask<String, Void, String>
{
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
StringBuilder result = new StringBuilder();
String type = params[0];
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
String register_url = "http://192.168.1.9/register.php";
if(type.equals("register"))
{
try
{
//Create data to send to server
JSONObject dataToSend = new JSONObject();
dataToSend.put("email", params[1]);
dataToSend.put("password", params[2]);
dataToSend.put("fname", params[3]);
dataToSend.put("lname", params[4]);
//Initialize and config request, then connect to server
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); //enable output (body data)
httpURLConnection.setRequestProperty("Content-Type", "application/json"); //set header
httpURLConnection.connect();
//Write data into server
OutputStream outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(dataToSend.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Read data response from server
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null)
{
result.append(line).append("\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
}
catch (IOException e)
{
return "Network Error";
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return result.toString();
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String result)
{
alertDialog.setMessage(result);
alertDialog.show();
}
Here's my PHP Code
<?php
$m = new MongoClient();
$db = $m -> ETESS;
$collection = $db -> members;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$fname = $data->fname;
$lname = $data->lname;
$encrypted_password = md5($password);
$document = array(
"email" => $email,
"password" => $encrypted_password,
"fname" => $fname,
"lname" => $lname
);
if($collection -> insert($document))
{
echo "Registered Successfully !";
$response["result"] = "success";
$response["message"] = "Registered Successfully !";
return json_encode($response);
}
else
{
$response["result"] = "failure";
$response["message"] = "Registered Failed";
return json_encode($response);
}
}
?>
I already added this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
with all of these code I always get "Network Error" when I clicked Register Button (I assume that it's catch IOException) but when I tried to send POST request by Advanced REST client, everything work perfectly.
Please kindly check my code if there are any mistake.
Thanks
Now I try to connect 192.168.1.9/register.php in browser in my mobile, and it's said
You don't have permission to access /register.php on this server.
I use wamp as web server
Thanks

Fetching Data from JSON using AsyncTask

I have created a fragment which if it is activated it will show MySQL data but it takes time to fetch the data and show it on a custom ListView.
I tried to implement AsyncTask so that while fetching the data you can do something else on the fragment while waiting but am having this error.
"FATAL EXCEPTION: main java.lang.NullPointerException"
Here is the code
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_markets,container,false);
//lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
lvMarkets.setAdapter(jAdapter);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params)
{
final String fin_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
Log.d(debug,response);
try
{
jsonArray =new JSONArray(response);
jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
}
catch (JSONException e)
{
Log.d(debug,e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d(debug,error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String> params=new HashMap<String,String>();
params.put("c_login",fin_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return fin_login;
}
}
Hope someone could point out what went wrong with my code and someone could also point out on how to fetch data on online much more faster.
Thanks...
Try this:
private void parsingValues() {
URL obj = null;
HttpURLConnection con = null;
String USER_AGENT = "Mozilla/5.0";
try {
//parameter to post
String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
obj = new URL("Your URI");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//getResponse
String subsResponse = response.toString();
final JSONObject responsesubs = new JSONObject(subsResponse);
//Here your parsing process
}
}
});
} else {
System.out.println("POST request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Call this method to your doinbackground of Asynhronous Task(parsingValues())

Displaying tables and colums from online database in Android Studio

I have designed an application with a successful login and register system in Android Studio. I am hosting my DB on hosting24.
I need to pull data from the DB and display it onscreen inside the application.
Can anyone suggest how to? I have a heap of code written for this application so any suggestions of what code is needed to see I will post. I am not too sure what code I would need to post here..
Scenario would be if a teacher logs into the application they will see a list of registered students and corresponding data related to those students.
<?php
$con = mysqli_connect("host", "username", "pw", "db");
$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$statement = mysqli_prepare($con, "SELECT * FROM Student");
mysqli_stmt_bind_param($statement, "ss",$FirstName, $LastName);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["FirstName"] = $FirstName;
$response["LastName"] = $LastName;
}
echo json_encode($response);
?>
Here is my java code
public class UserAreaActivity extends AppCompatActivity implements View.OnClickListener{
Button fetch;
TextView text;
EditText et;
HttpURLConnection urlConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
fetch= (Button) findViewById(R.id.fetch); //XML Button to get the data
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(UserAreaActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL("MY PHP URL");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
String firstName = Jasonobject.getString("FirstName");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(firstName)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Result in this is it hangs on fetching data for me. I just need a list of names to print to screen
First you will need to create a server side file which can fetch the data from database and post it as JSON (or other format if you prefer)
<?php
// Code to connect to database
// fetch and process the data
// print json echo json_encode($output)
?>
Suppose the above php file is at http://example.com/process.php
In Android you need to make an asynchronous HTTP request to the JSON API you created earlier (at http://example.com/process.php). One way is to use an AsyncHttpClient to fetch data
public void loadFromWeb(){
RequestParams params = new RequestParams();
AsyncHttpClient client = new AsyncHttpClient();
params.put("parameter", data);
client.post("http://example.com/process.php", params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
//process the response
//Do what you want with data, display in your layout
} catch (Exception e) {
//catch exception
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
// Process failure
}
});
}
You might want to read more about AsyncHttpClient for this.
Or you can have a look at other ways to make asynchronous calls, one such library is RetroFit

Android app can not connect to localhost server

I've created Database in my localhost, and want parse data from it with android app.I Create server with NodeJS and it works i can see the Database in browser, but my android app can't connect with this localhost server.
Here is my Java code.
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
public static ArrayList<String> titleList = new ArrayList<String>();
private static ArrayAdapter<String> adapter;
private static ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
// adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listView1, titleList);
// lv = (ListView) findViewById(R.id.listView1);
new JSONTask().execute("http://10.0.2.2:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
Log.i("Hakob_log",peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to POstExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
finally {
if(connection !=null) {
connection.disconnect();
}
try {
if(reader !=null) {
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
}
I thnk something wrong with this line
new JSONTask().execute("http://localhost:3000/api/people");
Thanks
Use the IP-address of the computer that you are referring to as localhost instead, this should solve your problem e.g.:
new JSONTask().execute("http://10.0.0.100:3000/api/people");

Categories