0

I am beginner in Android here I am attempting to connect my Android application to a simple php which is returning JSON objects.

Whenever I am running my application I am getting error unfortunately app has stopped on emulator and in ABD LOG I am getting PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline

 - 

**MainActivity.java**
---------------------


package jsonphp.com.jsonphp;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class MainActivity extends ActionBarActivity {

    private TextView responseTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.responseTextView = (TextView) this.findViewById(R.id.responseTextView);

        new GetAllCustomerTask().execute(new ApiConnector());

    }



    public void setTextToTextView(JSONArray jsonArray)
    {
        String s = "";
        for(int i=0;i<jsonArray.length();i++)
        {
            JSONObject jsonObject = null;
            try {
                jsonObject = jsonArray.getJSONObject(i);
                s = s +
                        "Name : "+jsonObject.getString("name")+"\n"
                        + "Age : "+jsonObject.getString("age")+"\n"
                        + "Address : "+jsonObject.getString("address")+"\n\n";
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
        this.responseTextView.setText(s);
    }


    private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
    {

        @Override
        protected JSONArray doInBackground(ApiConnector... params) {
            //this execute a bg thread

            return params[0].getAllCustomers();


        }

        protected void onPostExecute(JSONArray jsonArray)
        {
            setTextToTextView(jsonArray);
        }

    }



}

 - 

**ApiConnector.java**
---------------------
package jsonphp.com.jsonphp;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;

/**
 * Created by SWAPNIL on 20-06-2015.
 */
public class ApiConnector {

    public JSONArray getAllCustomers()
    {
        //URL for getting all customers

        String URL = "http://127.0.0.1/Android/test.php";

        // Get HttpResponse object from URL
        // Get HttpEntity from HTTP Response object
        HttpEntity httpEntity = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(URL);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            httpEntity = httpResponse.getEntity();
        }
        catch (ClientProtocolException ex)
        {
                    ex.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }


        //Converting HttpEntity into JSONArray

        JSONArray jsonArray = null;
        if(httpEntity != null)
        {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);
                Log.e("Entity Response : ",entityResponse);
                jsonArray = new JSONArray(entityResponse);
            }
            catch (JSONException ee)
            {
                ee.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return  jsonArray;
    }


}

Here my simple layout.

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/responseTextView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="60dp"
        android:textAlignment="center"/>

</RelativeLayout>

Along with that my test.php file.

<?php




$con = mysqli_connect("localhost","root","root","My_Database");

if(!$con)
{
    die("Could not connect : ".mysql_error());
}
/*mysqli_select_db("My_Database",$con);*/

$result = mysqli_query($con,"SELECT * From Customer");

while($row=mysqli_fetch_assoc($result))
{
    $output[] = $row;
}

print(json_encode($output));
mysqli_close($con);

?>

One more thing I have considered that HttpEntity, DefaultHttpClient, HttpGet, HttpResponse, ClientProtocolException, EntityUtils Above all are deprecated

0

2 Answers 2

0

first of all you should check weather the result returned is is json array format or json object format. the android code which you are using is being used to parse json array. And From the php code what i got is that you are json return is not an json array. convert that into json array and then use the same code in android you are using currently to parse it.

the second mistake is you are using the localhost. Your device or emulator is unable to make connection with that server. use ip 10.0.0.1 instead of 127.0.0.01 or make it some where online

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

Comments

0

CLIENT SIDE

    <LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Address"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextAddress" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert"
        android:onClick="insert"
        android:id="@+id/button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewResult" />
</LinearLayout>

Java code

import android.os.AsyncTask;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {

    private EditText editTextName;
    private EditText editTextAdd;


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

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextAdd = (EditText) findViewById(R.id.editTextAddress);


    }

    public void insert(View view){
        String name = editTextName.getText().toString();
        String add = editTextAdd.getText().toString();

        insertToDatabase(name,add);
    }

    private void insertToDatabase(String name, String add){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                String paramUsername = params[0];
                String paramAddress = params[1];


                String name = editTextName.getText().toString();
                String add = editTextAdd.getText().toString();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("name", name));
                nameValuePairs.add(new BasicNameValuePair("address", add));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://simplifiedcoding.16mb.com/insert-db.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
                textViewResult.setText("Inserted");
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, add);
    }

    @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);
    }
}

Add INTERNET PERMISSION TO YOUR MANIFEST FILE

**

SERVER SIDE

**

Sign up for free hosting at http://www.hostinger.co.uk/

Create a mysql datase with three colums:

  • id
  • name
  • address

CREATE A PHP FILE

<?php

      define('HOST','mysql.hostinger.uk');
      define('USER','u813815354_user');
      define('PASS','bhaq2010');
      define('DB','u813815354_db');

      $con = mysqli_connect(HOST,USER,PASS,DB);
      $name = $_POST['name'];
      $address = $_POST['address'];
    if(mysqli_query($con,$sql)){
        echo 'success';
      }
      else{
        echo 'failure';
      }
      mysqli_close($con);
    ?>

Comments

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.