I am fetching data from my sql database through c# JSON webservice and display it in table in android app on button press.
The connection between android app and c# webservice successfulyy establish but when I try to click button to view data it throughs exception "JSONArray fail".
I think there is some problem in json array but as I have just started to learn JSON web service so unable to figure out what is it. there is no error in program running success full.
c# webservice code is here :
public string getData()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand command = new SqlCommand("SELECT * FROM Student where CAST(Student.[date] AS DATE) = CAST(GETDATE() AS DATE)", con);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
return "1";
}
else
{
return "0";
}
}
android activity code is here :
public class StudentActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.student);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String rs = "";
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:51220/Service1.svc/getData?");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
// Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//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");
// Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();
rs=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting rs "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try
{
JSONArray jArray = new JSONArray(rs);
String re=jArray.getString(jArray.length()-1);
TableLayout tv=(TableLayout) findViewById(R.id.table);
tv.removeAllViewsInLayout();
int flag=1;
for(int i=-1;i<jArray.length()-1;i++)
{
TableRow tr=new TableRow(StudentActivity.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
if(flag==1)
{
TextView b6=new TextView(StudentActivity.this);
b6.setText("ID");
b6.setTextColor(Color.BLUE);
b6.setTextSize(15);
tr.addView(b6);
TextView b19=new TextView(StudentActivity.this);
b19.setPadding(10, 0, 0, 0);
b19.setTextSize(15);
b19.setText("First Name");
b19.setTextColor(Color.BLUE);
tr.addView(b19);
TextView b29=new TextView(StudentActivity.this);
b29.setPadding(10, 0, 0, 0);
b29.setText("Last Name");
b29.setTextColor(Color.BLUE);
b29.setTextSize(15);
tr.addView(b29);
TextView b4=new TextView(StudentActivity.this);
b4.setPadding(10, 0, 0, 0);
b4.setText("Project");
b4.setTextColor(Color.BLUE);
b4.setTextSize(15);
tr.addView(b4);
TextView b5=new TextView(StudentActivity.this);
b5.setPadding(10, 0, 0, 0);
b5.setText("Date and Time");
b5.setTextColor(Color.BLUE);
b5.setTextSize(15);
tr.addView(b5);
tv.addView(tr);
final View vline = new View(StudentActivity.this);
vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2));
vline.setBackgroundColor(Color.BLUE);
tv.addView(vline);
flag=0;
}
else
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("f1")+
", firstname: "+json_data.getString("f2")+
", lastname: "+json_data.getInt("f3") +
", project: "+json_data.getString("f4")+
", datetime: "+json_data.getString("f5"));
TextView b=new TextView(StudentActivity.this);
String stime=String.valueOf(json_data.getInt("f1"));
b.setText(stime);
b.setTextColor(Color.RED);
b.setTextSize(15);
tr.addView(b);
TextView b1=new TextView(StudentActivity.this);
b1.setPadding(10, 0, 0, 0);
b1.setTextSize(15);
String stime1=json_data.getString("f2");
b1.setText(stime1);
b1.setTextColor(Color.WHITE);
tr.addView(b1);
TextView b2=new TextView(StudentActivity.this);
b2.setPadding(10, 0, 0, 0);
String stime2=String.valueOf(json_data.getInt("f3"));
b2.setText(stime2);
b2.setTextColor(Color.RED);
b2.setTextSize(15);
tr.addView(b2);
TextView b3=new TextView(StudentActivity.this);
b3.setPadding(10, 0, 0, 0);
String stime3=String.valueOf(json_data.getInt("f4"));
b3.setText(stime3);
b3.setTextColor(Color.WHITE);
b3.setTextSize(15);
tr.addView(b3);
TextView b4=new TextView(StudentActivity.this);
b4.setPadding(10, 0, 0, 0);
String stime4=String.valueOf(json_data.getInt("f5"));
b4.setText(stime4);
b4.setTextColor(Color.RED);
b4.setTextSize(15);
tr.addView(b4);
tv.addView(tr);
final View vline1 = new View(StudentActivity.this);
vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
vline1.setBackgroundColor(Color.WHITE);
tv.addView(vline1);
}
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
});
}
}
I am using this in android manifest.xml file :
<uses-permission android:name="android.permission.INTERNET"/>
program is throwing this exception:
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
I am not getting any error related to NetworkOnMainThreadException.
I run my program both on android 2.2 and 2.3 emulator but facing same problem and I want to deploy my app on gingerbread only.
Thanks
-
have you checked that the json you are getting is valid json, and is in an array format, and the code you are showing for your webservice is just a get function not showing anything that is outputting the json you are trying to retrieve.Patrick Evans– Patrick Evans2013年08月24日 13:19:45 +00:00Commented Aug 24, 2013 at 13:19
-
1check stackoverflow.com/a/18418437/2398886Tarsem Singh– Tarsem Singh2013年08月24日 13:25:16 +00:00Commented Aug 24, 2013 at 13:25
-
possible duplicate of JSON to Android errorOscar– Oscar2013年08月24日 13:31:01 +00:00Commented Aug 24, 2013 at 13:31
-
@Patrick Evans I think you have point here I think I should convert my database data to JSON data but I didn't. Can you please help me how I can do it.user2684131– user26841312013年08月24日 13:35:54 +00:00Commented Aug 24, 2013 at 13:35
-
how are you outputting the data right now? Edit your question to show the code that is outputting it. I am not fluent in C# so i am not sure what the exact calls you need to output json, search SO or google sure you should find some tutorial that will show you.Patrick Evans– Patrick Evans2013年08月24日 13:41:44 +00:00Commented Aug 24, 2013 at 13:41
2 Answers 2
You should perform network operations in the sub-thread.
1 Comment
It's better to fetch (download)/upload data in a separate thread. Doing time consuming tasks on UI thread make it un-responsive. For such tasks, following two are prefered
- Async Task
- Threads
AsyncTask:
It's a class which have a few methods which help you to do time consuming work while updating the UI at the same time. For Example: If you want to search a specific word in a big document/ webpage, do the reading and searching stuff in doInBackground() (a method of AsyncTask class) and you can display a progress bar and notify the user with your progress with onProgressUpdate(). This gives your app more professional feel and at the same time helps you executing time consuming task in background.
Threads:
They are simple runnable threads. You can execute non UI stuff with these threads but you can't perform UI tasks in them (as UI is not thread safe). For dealing with UI in these threads, you will have to use Handlers, which is quite cumbersome for beginners to get a grip and understanding of them