In a Java Class, I have three List as fields in a class.
So I believe I made them available to the whole class? and all inner classes?
However, this does not work:
(For the example, I will only show one list here, not all three)
class Items extends ListActivity {
List<String> items = null; // field
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// stuff
items = new ArrayList<String>();
new Task().execute();
Log.d("Size", String.valueOf(items.size()));
}
class Task extends AsyncTask<String, String, Void> {
// in this subclass, I parse items from JSON and add to List "items".
items = add(item);
}
Once I exit the task, I seem to lose the items in the List. It Logs "size 0"; if I do it inside the task, it shows the proper amount of items. Am I missing a very basic point about the scope of List variables here?
EDIT: Below is the complete Task class (slightly cleaned up for posting)
class Task extends AsyncTask<String, String, Void> {
private InputStream is = null;
private String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category", Category));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} 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) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
Log.d("Items", item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No items!",
Toast.LENGTH_SHORT).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
I am not Android developer but isn't AsyncTask something like new Thread? If yes then you just see "size 0" because Log.d("Size", String.valueOf(items.size())); was executed before new task().execute(); updated your list.
You'll want to read through this tutorial
Basically, the default access level is package private (I could be wrong on the description), but basically it means that so long as you're in the same package you can see the member, but it is not visible to sub classes.
Try using the protected access level instead
Related
Here is a link: http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js with JSON objects. There are 261 objects with unique value (strings). How to get each object with numbers (2101, 2107 etc.) and 2 strings inside (picture and title)?
So this is my technologies AsyncTask:
ListView listView;
TechnologiesAdapter adapter;
ArrayList<Technologies> techList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
techList = new ArrayList<Technologies>();
new TechnologiesAsyncTask().execute("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
}
public class TechnologiesAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
//How to get the other objects?
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
You can get all of the names to a json array, then get every json object from the names in json array.
Following is a simple example.
private class DataAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("technology");
JSONArray nameArray = jsonObject.names();
final int size = nameArray.length();
for (int i = 0; i < size; i++) {
JSONObject object = jsonObject.getJSONObject(nameArray.getString(i));
// get id, title and pictures, etc
Log.d(TAG, nameArray.getString(i) + " " + object.getString("title") + " " + object.getString("picture"));
}
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
After you get the "technology" object just create another JSONObject from that like this:
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
// Get the 2101 object
JSONObject jObj3 = jObj2.getJSONObject("2101");
// Get the picture and title of 2101
String picture = jObj3.getString("picture");
String title = jObj3.getString("title");
Your JSON looks like it might be better suited to use a JSONArray instead of nested JSONObjects though.
JSONObject jPages=jQuery.getJSONObject("pages");
Iterator < String> keys = jPages.keys();
while(keys.hasNext()){
JSONObject jPageId=jPages.getJSONObject(keys.next());
//Action need to be performed
}
Hey guys im creating an app where it populates a list view with data from mysql, the data that will fill the list view consists of courseid, courseName and lecturerName. However when i click the button to view the list it creates the progress dialog as it should however it gets stuck and then the application stop responding.
Below is the code to which i believe is causing the error because the logcat mentions something about doInBackground which is in this class:
the log cat file is: http://gyazo.com/950bcce9d14f267f495a4801434c6151
i really appreciate your time and help, i further want to say i am sorry about my debugging skills im still getting used to android.
public class AllCoursesActivity extends ListActivity {
//progress dialog
private ProgressDialog pDialog;
//create json parser object to understand the php files that were created
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> courseList;
//url to get all the product list
private static String url_all_courses = "http://10.0.0.2/get_all_courses.php";
//JSON node Names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COURSES = "courses";
private static final String TAG_COURSEID = "courseid";
private static final String TAG_COURSENAME = "courseName";
//products JSON array
JSONArray courses =null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allcourses);
//hashmap for listview
courseList = new ArrayList<HashMap<String, String>>();
//loading courses in background thread
new LoadAllCourses().execute();
//GET list view
ListView lv = getListView();
}
class LoadAllCourses extends AsyncTask<String, String, String>{
//before starting the background thread show some progress dialog
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllCoursesActivity.this);
pDialog.setMessage("Loading Courses. Please Wait");
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
//getting all products from the URL
#Override
protected String doInBackground(String... args) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON String from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_courses, "GET", params);
//check log cat for json response
Log.d("All Products: ", json.toString());
try {
//checking for success TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1){
//it means courses were found
//Getting Array of products
courses = json.getJSONArray(TAG_COURSES);
//looping through all products
for (int i = 0; i < courses.length(); i++){
JSONObject c = courses.getJSONObject(i);
//storing each JSON Item in the variable
String courseid = c.getString(TAG_COURSEID);
String coursename = c.getString(TAG_COURSENAME);
//creating new HASHMAP
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to hashmap key => value
map.put(TAG_COURSEID, courseid);
map.put(TAG_COURSENAME, coursename);
//adding Hash list to array list
courseList.add(map);
}
}else {
//no courses found
//go back to dashboard
Intent i = new Intent(getApplicationContext(),MainScreenActivity.class);
//closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
//after completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url){
//dismiss the dialog after getting all the courses
pDialog.dismiss();
//updating ui from background thread
runOnUiThread(new Runnable() {
#Override
public void run() {
//updating parsed JSon data into list view
ListAdapter adapter = new SimpleAdapter(AllCoursesActivity.this, courseList,
R.layout.listcourse, new String[]{TAG_COURSEID, TAG_COURSENAME},
new int[]{R.id.courseid, R.id.coursename});
//updating listview
setListAdapter(adapter);
}
});
}
}
}
Edit: Sorry if i didnt include my JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//function to get url
//by making post or get method
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//making the http request
try {
//check for request method
if (method == "POST") {
//request method is post
//default http client
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();
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
}catch (Exception e){
Log.e("Buffer Error", "Error converting result" + e.toString());
}
//try parse the string to json object
try {
jObj = new JSONObject(json);
}catch (JSONException e) {
Log.e("JSON Parser", "Error Parsing data" + e.toString());
}
return jObj;
}
}
You're getting a NullPointerException and it's probably happening here:
Log.d("All Products: ", json.toString());
Search for "caused by" in your log cat output. It says that it was caused by attempting to use org.json.JSONObject.toString() on a null object. Add a check to make sure your object isn't null before you use it.
It looks like your JSON object is set to null on this line:
Log.d("All Products: ", json.toString());
Add a null check for your JsonObject before you log it.
It looks like we used the same tutorial for this, see my slightly different working implementation here:
https://github.com/dmnugent80/ShareApp/blob/master/app/src/main/java/com/share/daniel/share/MainActivity.java
Here is how to check if null:
if (json != null){
Log.d("MyApp", "All Products: " + json.toString());
}
else{
Log.d("MyApp", "json is null ");
}
Hey thank you for all the help but i realised what the problem was. You guys were right in that it could not return anything but this is because it wasnt connecting to the databaseproperly. i used my ip address from ip config and also i didnt link the php file correctly for example:
http://192.xxx.xx.x/android_api/get_all_courses.php
This above fixed the problem thanks for all the help and solutions
Android 4.2.2
I'm parsing a JSON string sent from PHP server. Parsing the same string gives this exception on random character number each time. Sometimes it's loaded successfully. The size of the input is 202858 bytes. I can't post it here as it's private data but I guess it's correctly formatted. If I run my app in debug/step-by-step mode it loads all the time! Also if the size of the response is smaller (fewer lines but not sure how many exactly) it also loads all the time.
Here is how I load the stream:
String JSONResp = "";
try {
URL u = new URL(params[1]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod(params[0]);
conn.connect();
/* Here is the new code. This works! */
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 4096);
StringBuilder sb = new StringBuilder();
String line = null;
while( (line = br.readLine()) != null ) {
sb.append(line + "\n");
}
JSONResp = sb.toString();
/* Old code starts here. This is not working!
// Read the stream
InputStream is = conn.getInputStream();
byte[] b = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1) {
baos.write(b);
}
JSONResp = new String(baos.toByteArray());
*/
JSONArray arr = new JSONArray(JSONResp);
//TODO read result form the input stream
_HTTP_code = 200;
return arr;
}
catch(Throwable t) {
_HTTP_code = ERROR_Throwable;
_HTTP_text = "Error";
_HTTP_body = "Could not parse response!";
Log.e("JSON", "JSONResp.length() = " + JSONResp.length() + ".");
t.printStackTrace();
}
The code is executed from a separate thread and this is what I found in the Android documentation:
Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overridable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.
I'm not sure if I understand that text correctly but I don't have more than one thread querying the server at the same time.
Any help would be appreciated.
public class GetResultTask extends AsyncTask<String, Void, String> {
Activity act;
private ProgressDialog pd;
private boolean isInternetConnected = true;
public GetResultTask(Activity _act){
this.act = _act;
pd = ProgressDialog.show(act, null, "Loading...", true );
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
pd.dismiss();
if(!isInternetConnected){
//Toast.makeText(getApplicationContext(), "Check your Network Connection", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("option", "getPeople"));
nameValuePairs.add(new BasicNameValuePair("val", params[0]));
String downloadedString = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/filename.php");
try {
// Execute HTTP Post Request
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
httppost.setEntity(ent);
//new
//HttpResponse response = httpClient.execute(httppost);
//System.out.println("Response");
HttpResponse response = httpclient.execute(httppost);
//System.out.println("Response is :-\n"+response);
InputStream in = response.getEntity().getContent();
StringBuilder stringbuilder = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bfrd.readLine()) != null)
stringbuilder.append(line);
//string returned as JSON
downloadedString = stringbuilder.toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch(UnknownHostException e){
isInternetConnected = false;
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
//System.out.println(downloadedString);
return downloadedString;
}
}
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;
}
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......