I have written a simple code on JSON Parsing using AsyncTask. I'm just displaying the response in TextView. I don't know whether it is right or wrong. Its working on GingerBread and showing NetworkOnMainThreadException on JellyBean. If I use StrictMode, its working on JellyBean and getting force close on GingerBread. How to write the code which support above Android 3.0 and below Android 3.0.
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
tv.setText(buffer);
}
}
}
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuffer buffer = new StringBuffer();
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
return buffer.tostring();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
tv.setText(result);
}}
}
otherwise you are running the read line operation in main thread
Make the InputStream is and Entity entity local field variables in the doInBackground() as return as result the string that you wanna set on the TextView...and on the onPostExecute() you just get the result (the string) and set it in the TextView straight on.
You should read inputStream data in doInBackground function, not in the onPostExecute. So construct StringBuffer in doInBackground append all lines to it and return StringBuffer.toString as result. In onPostExecute you will get what string as parameter.
Related
I am new to android and stuck with the following problem. This is my async task and I want to show result in next activity. I am getting the whole result in the console but in textview, it only shows the last name.
private class MyTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
String link = "http://www.amtechnologies.org/emergency/get_medicine.php";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(link));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("disease_name", result2));
System.out.println("Result2:"+result2);
UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
request.setEntity(form);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String result=EntityUtils.toString(entity);
result1 = result;
System.out.println("Result: "+result);
System.out.println("Result1: "+result1);
Intent i= new Intent(Medicines.this,View_medicines.class);
i.putExtra("result", result.toString());
startActivity(i);
}catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Next activty :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_medicines);
mnm=(EditText) findViewById(R.id.m3);
mi=(TextView) findViewById(R.id.m2);
nextbtn=(Button) findViewById(R.id.okmedi);
nextbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(View_medicines.this,Homepage.class);
startActivity(myIntent);
finish();
}
});
try {
Intent intent = getIntent();
String jsonArray=intent.getStringExtra("result");
jArray = new JSONArray(jsonArray);
System.out.println("Universe Acitivy Json Array: "+jArray);
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Change this part
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
to following
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.append(names);
mi.append(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
here my code for fetching values from web api. in my code no error is there. but in emulator doesn't show the values. please tell me where i done a mistake. let me know what is the correct code for that.
public class MainActivity extends ActionBarActivity {
Spinner sp1;
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=<random number>&action=Get Cities";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
}
public class Mysync extends AsyncTask<List<String>, List<String>, List<String>>{
#Override
protected List<String> doInBackground(List<String>... arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url1);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e(TAG,e.toString());
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
try {
list.add(arr.getJSONObject(i).getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
protected void onPostExecute(List<String> result){
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
}
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
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) {
// Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
}
Define List under the line
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=&action=Get Cities";
like : List<String> list ;
And Try to Change the line
List list = new ArrayList();
Via
list = new ArrayList();
and Change
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
Via
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item,result);
Hope this may help you!
public class getImagesTask extends AsyncTask<Void, Void, Void>
{
JSONObject json;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(GoogleSearchAPIExampleActivity.this, "", "Please wait...");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +"v=1.0&q="+strSearch+"&rsz=8&start=0" );
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", "http://technotalkative.com");
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println("Builder string => "+builder.toString());
json = new JSONObject(builder.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(dialog.isShowing())
{
dialog.dismiss();
}
try
{
JSONObject responseObject = json.getJSONObject("responseData");
JSONArray resultArray = responseObject.getJSONArray("results");
listImages = getImageList(resultArray);
Toast.makeText(getBaseContext(), "Length :" + listImages.size(), 5000).show();
// SetListViewAdapter(listImages);
System.out.println("Result array length => "+resultArray.length());
Intent in = new Intent(GoogleSearchAPIExampleActivity.this, Second.class);
startActivity(in);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Above is the code to get images using google image api. But here I get only 8 images for 1 search. What needs to be done if I want to get more than 8 images?
continuing my comment above, docs state
rsz rsz=4 This argument supplies an integer from 1–8 indicating the number of results to return per page.
so it seems like you're gonna have to page through the results on your own with new calls
read about the use of cursor here
I have a problem. I am starting my adventure with servlets and Android and I designed a simple servlet which writes "Hello world". Now I want to receive this message in my Android app. My code:
public class MyServlet extends Activity implements OnClickListener{
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/ServletExample/HelloServletExample";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
String output = null;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(new HttpGet(URL));
HttpEntity httpEntity = response.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//} catch (IOException e) {
// TODO Auto-generated catch block
//}
outputText.setText(output);
}
My servlet:
#WebServlet("/HelloServletExample")
public class HelloServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServletExample() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
I don't know why but my app crashes. I tried commenting out some lines and it turns out that what is the problem is this line:
HttpEntity httpEntity = response.getEntity();
Why?
if you are using API level >= 9 then no need to use AsyncTask for making network request from Ui Thread just add StrictMode.ThreadPolicy in Activity onCreate method as:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().
permitAll().build();
StrictMode.setThreadPolicy(policy);
Here is the class where i get JSON objects. In this code I get only one object and I don't really know how to return from the method, there is a Protected Void method where it is a settext method called and there is where the only JSON object goes.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://79.114.48.119/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("latitude");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
}
What I want to do is to have an array where i could store three kind of objects (exemple Latitude[1], Longitude [1], Description[1]; Latitude[2] etc... I would like the latitude and longitude to be as integers ). After this I will use a for loop to call a function with this 3 parameters. Could anyone help me or could give me some tips ?
Thank you!
Dont use AsyncTask, as it executes in background, and this is why it causes some problems for you.
And when you have your twitter arser working, integrate it in a AsyncTask. Code below is not tested.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
int i;
JSONObject json;
final static String URL = "http://localhost/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
for(i=0;i<2;i++){
new Read().execute("latitude");
try {
json = lastTweet("",i);
String result = json.getString(params[i]);
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public JSONObject lastTweet(String username,int i) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(i);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
}