httpclient (phpmyadmin) not working on Android 4.0+ - java

I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getServerData(null);
}
//i use my real ip here
public String getServerData(String returnString) {
System.out.println("going to connector class");
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
//the year data to send
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Logcat error (on 4.0+):
11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException
11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException
11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of
Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).
This is what I tried in Asynch:
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
String returnString = "";
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
protected Void doInBackground(String... params) {
try{
System.out.println("background in progress");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.

Since Android 3.0 you are not allowed to do network stuff on the main thread. Why? because network problems will lead to a slow ui. So you have to do all the http stuff in a new thread. You are on the right path but you made a mistake in your AsyncTask. Delete the empty doInBackground method in you async task and write #Override over your method.

android.os.NetworkOnMainThreadException
this eror comes With HoneyComb(3.0 or Later). you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.
you can See this for More Details WHY ICS Crashes your App
Try Using Below Code Snippet
new Thread(){
public void run(){
//do your Code Here
}
}.start();

Ok right...
After searching for few hours, making this question, then 10 minutes later, you find a solution...
Option 1:
I added this line:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:
Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html
//===========================================================================
Used ASyncTask as final (option 2).

why you are passing null in function of web connection and web service .?
getServerData(null);

Related

AsyncTask and onPreExecute

When I run the AsyncTask below, I can see the log messages. However progress bar wont change visibility.
Below, is my AsyncTask code.
class test extends AsyncTask<String, Void, String> {
private Context mContext;
public PostWav(Context context) {
mContext = context;
}
protected String doInBackground(String... params ) {
URL url= null;
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream inputStream;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
JSONObject object = new JSONObject();
try {
object.put("provider_id",1);
String message = object.toString();
HttpPost httppost = new HttpPost(url.toString());
httppost.setEntity(new StringEntity(message, "UTF8"));
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Accept", "application/json");
String boundary = "-------------" + System.currentTimeMillis();
httppost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
File file = getDir("test", Context.MODE_PRIVATE);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File wavFile = new File(file.getPath() + "/" + params[3]);
ContentType contentType = ContentType.create("audio/x-wav");
FileBody cbFile = new FileBody(wavFile,contentType,"sample");
builder.addPart("sample", cbFile);
builder.setBoundary(boundary);
httppost.setEntity(builder.build());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Header[] header = response.getHeaders("Location");
String location = String.valueOf(header[0].getValue());
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return location;
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
loading.setVisibility(View.VISIBLE);
record.setVisibility(View.INVISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String feed) {
Log.i("Async-Example", "onPostExecute Called");
loading.setVisibility(View.INVISIBLE);
record.setVisibility(View.VISIBLE);
}
}
I am uploading a .wav file to a my API. I did not included whole code this is basically all that I'm doing.
#greenapps Thanks mate your hint was more than enough for me to understand the problem.
Basically when I imported this class from another project I completely forgot the reason she was programmed like that.
I just had to remove .get() from the execute command and passed the methods to the post execute on the Task and everything when smoothly.
I am sorry for taking everyone's time, I really appreciated the help!
Here is the result i was looking for:
You would like to show the progress bar while the task is being completed, so you need to work around this statement.
Try to do the work in the following method(s):
doInBackground(int Progress)
OnProgressUpdate() to update the progress bar according to your ideas
For more read the following documentation.
Normally AsyncTask runs on the UI Thread, but I have the strong assumption that you are calling this from somewhere else than the UI Thread since you are passing the Context as a Parameter.
So you can use that.
#Override
protected void onPostExecute(String feed) {
Log.i("Async-Example", "onPostExecute Called");
activity.runOnUiThread(new Runnable(){
loading.setVisibility(View.INVISIBLE);
record.setVisibility(View.VISIBLE);
});
}
Also remove super.onPreExecute(); you dont need that
You have to change your constructor parameter from Context to Activity or it will be a bit more complicated.

Perform AsyncTask on Android / Posting JSON

I am working on an android app, and am running into some troubles with registering users. I want to post a JSON object to my server and receive one back. I can successfully create a JSON object with the right information but when I go to post it I get a NetworkOnMainThreadException or my HttpClient class returns null when it should be returning a JSONObject and I am very confident that my web server works correctly. I understand that you cannot connect to the network on the main thread and have created an HttpClient class that uses AsnycTask (although probably not correctly). I have been working on this for quite a while and would appreciate any guidance in the right direction.
//Main activity
#Override
public void onClick(View arg0) {
if(!(isEmpty(name) || isEmpty(username) || isEmpty(password) || isEmpty(email))) {
user = new JSONObject();
try {
user.put("username", username.getText().toString());
user.put("name", name.getText().toString());
user.put("email", email.getText().toString());
user.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
jRegister = new JSONObject();
try {
jRegister.put("apiToken", Utilities.apiToken);
jRegister.put("user", user);
Log.i("MainActivity", jRegister.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
//
HttpClient client = new HttpClient(url, jRegister);
result = client.getJSONFromUrl();
try {
if(result != null)
tv.setText(result.toString(2));
else
tv.setText("null");
} catch (JSONException e) {
e.printStackTrace();
}
}else {
tv.setText("");
}
}
HttpClient Class
public class HttpClient extends AsyncTask<Void, Void, JSONObject>{
private final String TAG = "HttpClient";
private String URL;
private JSONObject jsonObjSend;
private JSONObject result = null;
public HttpClient(String URL, JSONObject jsonObjSend) {
this.URL = URL;
this.jsonObjSend = jsonObjSend;
}
public JSONObject getJSONFromUrl() {
this.execute();
return result;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject jObject) {
result = jObject;
}
private static String convertStreamToString(InputStream is) {
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();
}
}
return sb.toString();
}
}
I understand that you cannot connect to the network on the main thread
and have created an HttpClient class that uses AsnycTask (although
probably not correctly).
You are right you have not implemented it the right way.
In your onClick events (still on Main thread) you performed a network activity causing the error:
HttpClient client = new HttpClient(url, jRegister);
result = client.getJSONFromUrl();
Instead you should run the network operation inside of the AsnycTask
public class GetJsonTask extends AsyncTask<Void, Void, JSONObject >{
private String URL;
private JSONObject jsonObjSend;
public GetJsonTask(String URL, JSONObject jsonObjSend) {
this.URL = URL;
this.jsonObjSend = jsonObjSend;
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject jsonObjRecv;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
}
}
catch (Exception e) {
e.printStackTrace();
}
return jsonObjRecv;
}
protected void onPostExecute(JSONObject result) {
try {
if(result != null)
tv.setText(result.toString(2));
else
tv.setText("null");
} catch (JSONException e) {
e.printStackTrace();
}
}else {
tv.setText("");
}
}
}
Then you call your async in onclik method like this:
public void onClick(View arg0) {
//.......
GetJsonTask client = new GetJsonTask(url, jRegister);
client.execute();
}
One problem in your code is that your expectations of AsyncTask aren't quite right. In particular this function:
public JSONObject getJSONFromUrl() {
this.execute();
return result;
}
AsyncTask runs the code in the doInBackground() function in a separate thread. This means that once you call execute() you have two parallel lines of execution. You end up with what's called a Race Condition. When you reach the return result line, a couple of things can be happening:
doInBackground() hasn't run and therefore result is still has the default value. In this case null.
doInBackground() can be in the middle of the code. In your particular case because it doesn't modify result then this doesn't affect you much. But it could be on any line (or middle of a line sometimes if operations aren't atomic) when that return happens.
doInBackground() could've finished, but since onPostExecute() runs on the UI thread it has to wait until your onClick handler is finished. By the time onPostExecute() has a chance to run onClick already tried to update tv with whatever it was that getJSONFromUrl returned, most likely null.
The way to set up tasks with AsyncTask is to give it the information it needs to do it's work, start it up with execute, and since you can't know how long it will take to complete, let it handle the finishing steps of the task.
This means that after calling execute you don't wait around for it's result to update views (like in your case), but rather rely on the AsyncTask's onPostExecute or related methods to take over the next steps.
For your case this would mean that your onPostExecute should look something like:
protected void onPostExecute(JSONObject result) {
try {
if(result != null)
tv.setText(result.toString(2));
else
tv.setText("null");
} catch (JSONException e) {
e.printStackTrace();
}
}

Getting data from PHP in Android

I've seen several tutorials for this, but they're all older than the Android update that prevents network calls in the main thread. I tried moving the code that called it to a RetrieveFeedTask, but that didn't help me, because I then had no way to get the data in my main thread. Here's what I did:
class RetrieveFeedTask extends AsyncTask <String, Void, String>
{
private Exception exception;
private String doInBackground()
{
String returnString = "sample";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample_array.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
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 converting result "+e.toString());
}
//paring data
int step_num;
String description;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
step_num=json_data.getInt("step_num");
description=json_data.getString("description");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No step found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
//System.out.println(result);
return result;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
}
Then in the main thread, I did this:
AsyncTask<String, Void, String> returnString = new RetrieveFeedTask().execute();
So how do I get that information to use in the main thread?
You're almost ok with that but there are 2 errors:
You're overloading the doInBackground method that could never get called.
implement your stuff inside the "currently" empty doInBackground implementation.
If you want to get your data back on your main thread you can:
use the runOnUiThread Method
create an Anonymous Inner Class inside your activity that will extend your asynctask and overrides the onPostExecute method. ( which runs on the ui thread )
:)
You can make one web-service that returns data you need in JSON format. Put that on to your server.
Now call that web-service using android. This way You can get data from PHP to android
Implement your current code in empty doInBackground block
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
return string from above method, will be received in onPostExecute method, that you need to implement in your code too, which is actually missing at present.

Does it counts as a REST?

I am trying to figuring out about REST method. I watched few videos from google conference about REST technology but what I saw was app's implementation of connectivity with database. So I would like to know if my code would count as a REST.
PHP code:
<?php
mysql_connect("localhost","*****","********");
mysql_select_db("********");
$cname = mysql_real_escape_string($_REQUEST['cname']);
$q=mysql_query("SELECT mdl_course_sections.summary FROM mdl_course, mdl_course_sections WHERE mdl_course.id = mdl_course_sections.course AND mdl_course.fullname = '$cname' AND mdl_course_sections.section > 0");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
JAVA code:
public class CourseSegmentsActivity extends ListActivity{
String courseName = null;
String segmentName = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent i = getIntent();
courseName = i.getStringExtra("courseName");
ArrayList<HashMap<String,String>> myCoursesList = new ArrayList<HashMap<String,String>>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("cname",""+courseName));
InputStream is = null;
String result = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("****************");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-10"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int ii=0;ii<jArray.length();ii++){
JSONObject json_data = jArray.getJSONObject(ii);
segmentName = json_data.getString("summary");
HashMap<String,String> map = new HashMap<String, String>();
map.put("summary", segmentName);
myCoursesList.add(map);
}
} catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, myCoursesList,R.layout.course_segments_list_layout,
new String[] {"summary"}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
If not what I am missing?
No, you are NOT. if you follow REST standards, you should be using http protocol efficiently. As per REST standard,
if you are reading data - use GET
if you are reading meta-data - use HEAD
if you are writing data - use POST
if you are modifying data - use PUT
if you are deleting - use DELETE,
please refer to the w3c specification of http protocol(RFC2616) for further info.
No, you are using POST to retrieve data. However, POST is meant to be used to edit existing data.
Query strings are also rather unlikely when using REST - usually you use the URL to specify resources
Have a look at http://en.wikipedia.org/wiki/REST#RESTful_web_services

How to retrieve data from json array and display in textview?

I've been using the coding from an example from this link: The code is as shown below:
public class food extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result=null;
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
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 converting result "+e.toString());
}
//paring data
int fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
Now my question is how to pass this data to a list view, like for each iteration a list item must be added with the retrieved data.
Please help me
Thanks in advance
You are already getting strings in below code, Why don't you use that.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
//fdname and fd_id you are getting it right,
If your code is not working then add what problem you are facing.
according to your response/result from the server below code is working for me and giving output in string ,
try {
String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
JSONArray array;
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(0);
String id_fd = obj.getString("FOOD_ID");
String name_fd = obj.getString("FOOD_NAME");
Log.d("JSONArray", id_fd+" " +name_fd);
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please use it according to your need.
The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.
In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:
<TextView
android:id="#+id/textView1"
....

Categories