0

I'm trying to send parameters to php to mysql via the POST method. It seems that my code doesn't load the parameters into httpPost. When debugging I see that params are null under httpPost variable and it seems that the entity isn't being picked up. Please any help would be greatly appreciated. I'm using android studio.

Main Activity

public class MainActivity extends ActionBarActivity {

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


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

public void setSave(View view) {
    new TestSQL().execute();

}

private class TestSQL extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
        WriteToDatabase write = new WriteToDatabase();
        String a = "1";
        String b = "2";
        String c = "3";
        String d = "4";
        String e = "5";
        String f = "6";
        String g = "7";
        JSONObject json1 = write.writeDB(a, b,
                c, d, e, f, g);
        return json1;
    }
}

WriteToDatabase.java to build List Namevaluepairs

public class WriteToDatabase {

private JSONParser test;

// URL of the PHP API
private static String link = "http://192.168.1.102/test/test2.php";

public JSONObject writeDB(String a,String b,
                          String  c, String d,String e,String f,String g) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name", b));
    params.add(new BasicNameValuePair("description",
            c));
    params.add(new BasicNameValuePair("add", d));
    params.add(new BasicNameValuePair("city", e));
    params.add(new BasicNameValuePair("cat", a));
    params.add(new BasicNameValuePair("uid", f));
    params.add(new BasicNameValuePair("day", g));
    JSONParser test = new JSONParser();
    JSONObject json = test.getJSONFromUrl(link, params);

    return json;

}

}

my JSONParser.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
     // With or without HTTP.UTF_8 won't work
        DefaultHttpClient httpClient = new DefaultHttpClient();
        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        httpPost.setEntity(ent);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            Log.i("RESPONSE", EntityUtils.toString(httpEntity));
        }
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
}

}

and my Logcat

11-15 21:30:04.273      818-836/com.example.julian.testforsql E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.IllegalStateException: Content has been consumed
        at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
        at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
        at com.example.julian.testforsql.JSONParser.getJSONFromUrl(JSONParser.java:57)
        at com.example.julian.testforsql.WriteToDatabase.writeDB(WriteToDatabase.java:30)
        at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:62)
        at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:50)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

            at java.util.concurrent.FutureTask.run(FutureTask.java:137)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)             at java.lang.Thread.run(Thread.java:856)

loanerr
  • 1
  • 1

2 Answers2

0

Remove this line :

    if (httpEntity != null) {
        Log.i("RESPONSE", EntityUtils.toString(httpEntity));
    }

I just found out that calling EntityUtils.toString(httpEntity)) is counted for using the used (consumed) Entity hence getting you the exception.

I know this from @dvm's answer in this question (Thanks to him) :

IllegalStateException: Content has been consumed

Community
  • 1
  • 1
Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
  • Thank you! That solved my IllegalStateException but I'm still having a problem with the parameters attaching to the httpPost variable. I wonder if i'm using this code wrong somehow-httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); – loanerr Nov 16 '14 at 13:30
0

For some reason, maybe of migrating from Eclipse to Android Studio, or some other reason I can't figure out, I was not able to put the parameters into the httpPost via the entity. I found thisenter link description here and followed the steps how to send it via json object and then modified my php code. The final result was:

MainActivity:

public class MainActivity extends ActionBarActivity {

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


@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);
}
public void setSave(View view) {
    new TestSQL().execute();

}

private class TestSQL extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
        WriteToDatabase write = new WriteToDatabase();
        String a = "1";
        String b = "2";
        String c = "3";
        String d = "4";
        String e = "5";
        String f = "6";
        String g = "7";
        JSONObject json1 = null;

        try {
            json1 = write.writeDB(a, b,
                    c, d, e, f, g);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return json1;
    }
}

}

WriteTodatabase.class as if building parameters

public class WriteToDatabase {


// URL of the PHP API
private static String link = "http://192.168.1.102/test/test.php";

public JSONObject writeDB(String a,String b,
                          String  c, String d,String e,String f,String g) throws JSONException{

    JSONObject jsonObj = new JSONObject();
    jsonObj.put("name", b);
    jsonObj.put("description",c);
    jsonObj.put("add", d);
    jsonObj.put("city", e);
    jsonObj.put("cat", a);
    jsonObj.put("uid", f);
    jsonObj.put("day", g);

    JSONArray postjson=new JSONArray();
    postjson.put(jsonObj);

    JSONParser test = new JSONParser();
    JSONObject json = test.getJSONFromUrl(link, postjson,jsonObj);

    return json;

}

}

JSONparser

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, JSONArray postjson, JSONObject json) {

    // Making HTTP request
    try {

        HttpPost httpPost = new HttpPost(url);
        // Post the data:
        httpPost.setHeader("json", json.toString());
        httpPost.getParams().setParameter("jsonpost", postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);

        // for JSON:
        if (response != null) {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(sb.toString());
        }


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return json;
}

}

and modified my php code. I had made it before by reading POST variables but now how to reassign them as such, I put this code at the top of php and then fed it with an insert statement to mysql:

$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
  

/ echo "--------------\n";

$_POST ['name'] = $data->name;
$_POST ['description']= $data->description;
$_POST ['add']= $data->add;
$_POST ['city']= $data->city;
$_POST ['uid']= $data->uid;
$_POST ['day']= $data->day;
$_POST ['cat']= $data->cat;
 

Hope this helps someone sometime.

Community
  • 1
  • 1
loanerr
  • 1
  • 1