Parse Simple Json response - java

Am trying to parse this Json response. For some weird reason its not working. Please bear with me . I really suck at Json.
Here is the Url am trying to parse:
This is the code am using to parse it:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), "started", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject myJson = new JSONObject(str);
String grande = myJson.getString("title");
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}
}
i just need to parse the Title and descrption only. thanks

Its seems you have not parsed properly
Change your try block with the following code
try{
JSONObject myJson = new JSONObject(str);
JSONObject entityObject = myJson.getJSONObject("entity");
// Parsing title
JSONOBject titleObject = entityObject.getJSONObject("title");
String grande = titleObject.getString("$t");
// Do the same for Description as well (Like above two line)
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}

I think that toast message of yours (in doInBackground) is posing problems, try commenting it out and then check!
Moreover, best practice is to send the response to onPostExecute as an argument and then parse the Json in onPostExecute

try like this,
#Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject myJson = new JSONObject(result);
JSONObject entry = results.getJSONObject("entry");
JSONObject grande = results.getJSONObject("title");
String title = grande.getString("$t");
Toast.makeText(getActivity(), title, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}

Related

POST JSON data to server

I am working on POST JSON data to server. It is working fine with a tutorial this link but it is not working with this with some of the required data changes. Is there anything related to Javaservlet and PHP links , as the first link is designed using Javasevlet and the other is in PHP ?
public static String POST(String url)
{
InputStream inputStream = null;
String result = "";
try {
org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
String json = "";
JSONObject jsonObject=new JSONObject();
/*JSONArray jsonArray=jsonObject.getJSONArray("object");
JSONObject jsonObject2=jsonArray.getJSONObject(10);*/
jsonObject.putOpt("id",2);
jsonObject.putOpt("address","myaddress");
json=jsonObject.toString();
StringEntity se=new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse=httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// person = new PersonLocator();
// person.setAddresS(myLocationText.getText().toString());
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
Thanks for the help in advance

Why doesn't the function get data from php in android?

I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.
Here is the Java function:
public class PostDataGetRes extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postRData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
public void postRData() {
String result = "";
InputStream isr = null;
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/appservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", email));
nameValuePairs.add(new BasicNameValuePair("stringdata", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
resultView.setText("Inserted");
HttpEntity entity = response.getEntity();
isr = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
//"User ID : "+json.getInt("user_id")+"\n"+
//"Name : "+json.getString("first_name")+"\n"+
//"Email : "+json.getString("email")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
resultView.setText("Done");
}
And here is php code:
if($id){
$query = mysql_query("SELECT first_name FROM users where email = '$id' ");
while($row=mysql_fetch_assoc($query)){
$selectedData[]=$row;
}
print(json_encode($selectedData));
}
Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.
At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.
AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI.
Here is a not much different example how it uses methods you have in AsyncTask class:
class Logging extends AsyncTask<String,String,Void>{
JSONObject json=null;
String output="";
String log=StringCheck.buildSpaces(login.getText().toString());
String pas=StringCheck.buildSpaces(password.getText().toString());
String url="http://www.mastah.esy.es/webservice/login.php?login="+log+"&pass="+pas;
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Operation pending, please wait", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", "User-Agent");
HttpResponse response;
try {
response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
output=result.toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Connection problems", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Conversion problems", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void w) {
try {
json = new JSONObject(output);
if(json.getInt("err")==1){
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
}else{
String id_user="-1";
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
JSONArray arr = json.getJSONArray("data");
for(int i =0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
id_user = o.getString("id_user");
}
User.getInstance().setName(log);
User.getInstance().setId(Integer.valueOf(id_user));
Intent i = new Intent(getApplicationContext(),Discover.class);
startActivity(i);
}
} catch (JSONException e) {
}
super.onPostExecute(w);
}
}
PHP file content:
$data = array(
'err' => 0,
'msg' => "",
'data' => array(),
);
$mysqli = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if($mysqli->connect_errno){
$data['err'] = 1;
$data['msg'] = "Brak polaczenia z baza";
exit(json_encode($data));
}
if(isset($_GET['login']) && isset($_GET['pass'])){
$mysqli->query("SET CHARACTER SET 'utf8';");
$query = $mysqli->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$data['err']=1;
$data['msg']="User banned";
exit(json_encode($data));
}else{
$query = $mysqli->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$query = $mysqli->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
if($query->num_rows){
$data['msg']="Logged IN!";
$query = $mysqli->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
$data['data'][]=$query->fetch_assoc();
exit(json_encode($data));
}else{
$data['err']=1;
$data['msg']="Wrong login credentials.";
exit(json_encode($data));
}
}else{
$data['err']=1;
$data['msg']="This login doesn't exist.";
exit(json_encode($data));
}
}
}else{
$data['err']=1;
$data['msg']="Wrong login credentials";
exit(json_encode($data));
}
I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.
Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:
if(json.getInt("err")==1){
//something went wrong
}else{
//everything is okay, get JSON, inform user, start new Activity
}
Also here is the way I used $data['data'] to get JSON response:
if($query->num_rows){
while($res=$query->fetch_assoc()){
$data['data'][]=$res;
}
exit(json_encode($data));
}

Android - How to Handle an Async Http Crash

My app is currently crashing whenever it cannot connect to the server. How do I handle this, and instead let the user know that the server is down and to try again.
private void sendPostRequest(String givenEmail, String givenPassword) {
class SendPostRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String emailInput = params[0];
String passwordInput = params[1];
String jsonUserInput = "{email: " + emailInput + ", password: "
+ passwordInput + "}";
try {
HttpClient httpClient = new DefaultHttpClient();
// Use only the web page URL as the parameter of the
// HttpPost argument, since it's a post method.
HttpPost httpPost = new HttpPost(SERVER_URL);
// We add the content that we want to pass with the POST
// request to as name-value pairs
json = new JSONObject(jsonUserInput);
jsonString = new StringEntity(json.toString());
httpPost.setEntity(jsonString);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor does
// nothing.
// So we can't initialize InputStream although it is not an
// interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.i(LOGIN, "ClientProtocolException");
cpe.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException ioe) {
Log.i(LOGIN, "IOException");
ioe.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOGIN, result);
try {
serverResponse = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if ((serverResponse.has("status"))
&& (serverResponse.get("status").toString()
.equals("200"))) {
Toast.makeText(getApplicationContext(), "SUCCESS!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Email/Password!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
sendPostRequestTask.execute(givenEmail, givenPassword);
}
LogCat Error Log
11-11 16:26:14.970: I/R.id.login_button(17379): IOException
11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection to http://* refused
11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
I can see that you are already catching the Exceptions and have a String as parameter type to onPostExecute. From inside the exceptions, you can pass a string like "error" to the onPostExecute, whenever an error occurs. Inside the onPostExecute you can check:
if the string is equal to "error":
then create a Alert dialog box from within `onPostExecute` and show it.
else:
continue as desired
Ideally a boolean would do the trick but since you already have a string, you can also use that. Otherwise you can have a struct with a string and a boolean and then pass it to onPostExecute. Hope it gives you the idea.
Or you can create new Object
public class AsyncTaskResult<T> {
private T result;
private Exception error;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public void setError(Exception error) {
this.error = error;
}
}
and pass it to onPostExecute
return new AsyncTaskResult<String>(result)
or
return new AsyncTaskResult<String>(exception)
in onPostExecute you may check exception exists or not
asynctaskresult.getError() != null
You can use droidQuery to simplify everything and include HTTP error handling:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.timeout(1000)
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
JSONObject serverResponse = (JSONObject) args[0];
//handle response
}
})
.error(new Function() {
#Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
//toast shows the error code and reason, such as "Error 404: Page not found"
Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
}
}));

Android AsyncTask: How to handle the return type

I am working on an Android application that executes an http POST request, and the tutorial I followed was resulting in an android.os.NetworkOnMainThreadException
The original code was something like this.
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 {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
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 this class was invoked with this line.
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
After changing this to an AsyncTask class, the code looks like this.
class JSONParser extends AsyncTask<String, Void, JSONObject>{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// variables passed in:
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
#Override
protected JSONObject doInBackground(String... args) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException 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;
}
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
}
My question is, how do I return a JSONObject from this new AsyncTask class?I can see that jObj is being returned in doInBackground(), but I am not sure where it is being returned to.
What do I need to modify or how do I need to call my new JSONParser class so that it is returning a JSONObject?
Have a look at this code, it may give you an insight as to how to deal with the parsing of JSON objects. I am just posting the onPostExecute function for now because you seemed to have all the rest figured correctly.
As for your doubt as to where the data object from the doInBackground is returned, it is automatically sent to the onPostExecute where you can further on parse it.
#Override
protected void onPostExecute(JSONObject result)
{
try
{
JSONObject data = result.getJSONObject("data");
// whatever your JSON tag may be, in this case its data.
if (data.isNull("data"))
{
// action to handle null JSON object.
}
else
{
JSONArray jarray = data.getJSONArray("data");
int len=jarray.length();
for (int i = 0; i < jarray.length(); i++)
{
JSONObject obj = (JSONObject) jarray.get(i);
String instanceName = obj.getString("instanceName");
//extract data by whatever tag names you require, in this case instanceName.
}
}
}
catch (JSONException je)
{
je.printStackTrace();
Log.d(TAG, "Error: " + je.getMessage());
}
}
}
from your doInBackground Method
#Override
protected JSONObject doInBackground(String... args) {
return jObj;
}
your return your JsonObject to
#Override
protected void onPostExecute(JSONObject jObj) {
// Here you get your return JsonObject
}
An Async Task has 3 attribures
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
The point you need to understand is that you are creating a object of Async Task Class While calling new JSONParser(loginURL, params);
The solution is that create a public result variable in your Async class and the call execute() on the object of class and then access the public object from the object.
I can see that jObj is being returned in doInBackground() but I am not
sure where it is being returned to.
The result of doinBackground() is received as a parameter in onPostExecute(). You are returning a json object in doinBackground() which is a parameter to onPostExecute().
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
Usage
new JSONParser().execute("url);
class JSONParser extends AsyncTask<String, Void, JSONObject>{
//string parameter to doInBackground()
//JSONObject - result returned in doInBackground() received as a param in onPostExecute()
}
You can also pass paramters to the constructor of your asynctask
new JSONParser("url",params).execute();
In your asynctask;
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}

httpPost not working using asynctask - giving invalid index, size is 0 exception

In order to avoid executing the http relating things in the UI thread, i migrated my code inside asynctask, before that, it was working fine on versions before 3.0 -- however, after literally copy pasting the code inside asynctask, it started to giving the invalid index, size is 0 exception. Whenever I need to use the method I am applying the call --
new dataRetrievalViaAsyncTask().execute(url, null, null); --
Whats wrong down there ?
class dataRetrievalViaAsyncTask extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
// convert response to string
return null;
}
protected void onPostExecute()
{
try
{
Log.i("tag","before : BufferedReader reader = new BufferedReader(new Inp");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
try
{
Log.i("tag", "before : jsons ");
jArray = new JSONArray(result);
JSONObject json_data = null;
Log.i("tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
uid = json_data.getInt("uid");
item1= json_data.getString("item1");
item2 = json_data.getString("item2");
item3 = json_data.getString("item3");
item4 = json_data.getString("item4");
item5 = json_data.getString("item5");
item6 = json_data.getString("item6");
favorited = json_data.getString("favorited");
currentList.add(new itemClass(uid, item1 item2)); //there is a constructor for this in the itemClass
itemClass toSendToOffline = new itemsClass(uid, item1, item2, item3, item4, item5, item6, favorited);
myDBHelper.insertFromOnlineToDBtoSendToOffline();
}
} catch (JSONException e1)
{
Toast.makeText(getBaseContext(), "Not Found", Toast.LENGTH_LONG).show();
} catch (ParseException e1)
{
e1.printStackTrace();
}
super.onPostExecute(null);
}
}
(mainly the code is stopping at --
HttpResponse response = httpclient.execute(httppost);
I can not see nameValuePairs variable initialized anywhere, which is actually causing problem.
class dataRetrievalViaAsyncTask extends AsyncTask<Void, Void, String>
{
String URL = "";
public dataRetrievalViaAsyncTask( String url )
{
URL = url;
}
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... f_url)
{
String result="";
try
{
result=fetchdataFromServer(URL);
}
catch (JSONException e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
// See your results as string //result
}
public JSONObject getJsonObjectToRequestToServer(String plid) throws JSONException
{
JSONObject parms = new JSONObject();
parms.put("user_id", "");
parms.put("app_key", "xyz");
parms.put("secret", "abc");
parms.put("token", "");
parms.put("playurl", "1");
parms.put("mode", "playlistdetail");
parms.put("playlist_id", plid);
return parms;
}
public String fetchdataFromServer(String url) throws JSONException
{
String stringresponce = null;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject parms = getJsonObjectToRequestToServer("1");
StringEntity se;
se = new StringEntity(parms.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
#SuppressWarnings("rawtypes")
ResponseHandler responseHandler = new BasicResponseHandler();
stringresponce = httpClient.execute(httpPost, responseHandler);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return stringresponce;
}
}
put this code in your code and pass arguments ass you need this is the way how i request to server and get json response as string from result variable pass arguments to your url as i passed by making json object then convert them to string
then execute like this............
dataRetrievalViaAsyncTask asyncTask=new dataRetrievalViaAsyncTask(Yoururl);
asyncTask.execute();
hope this will help if you have some issues please post here thanks......

Categories

Resources