Display an XML on main thread - java

I have a little issue about a little thing I don't understand.
It's just a simple request: how do I display an xml I just got in a thread?
There is my method postData to get the xml, I make it display in a log.v as you can see below in the code, but I can't display it to a TextView out of the thread.
public class RecupXml_Activity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
campagne = (TextView) findViewById(R.id.campagneTest);
postData(user, password);
}
public void postData(final String login, final String password) {
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null;
#Override
public void run() {
try {
URLConnection urlConnection;
String body = "login=" + URLEncoder.encode(login, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8");
url = new URL("http://3pi.tf/apps/sms/");
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", "" + body.length());
OutputStreamWriter writer = null;
BufferedReader reader = null;
writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(body);
writer.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((buffer = reader.readLine()) != null) {
theCampagneXml = buffer;
}
Log.v("test", "xml = " + theCampagneXml);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("salut voici ta campagne : " + theCampagneXml);
}
});
}
});
background.start();
}
}
It appears in my Log but not in the TextView:/ I have a white empty Activity.

The problem is that you call postData() on UI-tread, meaning that the method also returns theCampagneXml on UI-thread, while your network operation goes on a worker thread. The following code with some changes and additions fixes the problem:
public class MainActivity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml; // new
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campagne = (TextView) findViewById(R.id.text);
postData(user, password); // new
}
public void postData(final String login, final String password) { // note: the return type has been changed
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null; // new
#Override
public void run() {
try {
// no changes here but declaring `theCampagneXml` as class member
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("hello, here is your XML : "+ theCampagneXml);
}
});
}
});
background.start();
}
}
Once the network operation is done and theCampagneXml is initialized, use post() for the TextView campagne that runs on UI-thread.
Additional info can be found in Processes and Threads.

Related

android class async upload reference

I am back from taking a few years break in programming. Today I am trying to access my webserver from android and I have some code I recycled from back in the day. The code used to work, but, lo and behold, today it has an error. Can someone help me figure this out?
Here is my main class:
public class login extends AppCompatActivity {
Button join;
TextView clientid;
EditText username, password;
_upload upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
upload = new _upload();
String android_id = Secure.getString(login.this.getContentResolver(),
Secure.ANDROID_ID);
join = findViewById(R.id.join);
clientid = findViewById(R.id.clientid);
clientid.setText(android_id);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}});
}
public void login(){
String id = username.getText().toString();
if (id.isEmpty()) { username.setError("required");username.requestFocus();return; }
String pw = password.getText().toString();
String cid = clientid.getText().toString();
String[] params = new String[3];
params[1]="username::" + id;
params[2]="password::" + pw;
params[3]="cid::" + cid;
new upload.send(login.this, "dump.php", params);
Toast.makeText(this, id + " " +pw+ " "+cid, Toast.LENGTH_LONG).show();
}
}
my error is in the line new upload.send(login.this, "dump.php", params);
error: cannot find symbol
new _upload.send(login.this, "dump.php", params);
^
symbol: class send
location: class _upload
this is my second class, the one that used to work:
public class _upload extends AppCompatActivity {
HttpURLConnection conn = null;
String Return;
String homeurl = "removed";
String roomurl = "";
String param;
Context ctx;
String er;
public void location(Context context, String url, String params){
ctx = context;
roomurl = url;
try {
param = "lola=" + URLEncoder.encode(params, "UTF-8");
new sendStatusChange_Server().execute("");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void send(Context context, String url, String params[]){
ctx = context;
roomurl = url;
int total = params.length;
int i = 0;
while(i<=total-1) {
if (i==0) {
try {
String[] keyval = params[0].split("::");
param = keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
else{
try {
String[] keyval = params[i].split("::");
param = param + "&" + keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
}
new sendStatusChange_Server().execute("");
}
public class sendStatusChange_Server extends AsyncTask<String, String, Void> {
protected Void doInBackground(String... params) {
try {
updateserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(er!=null){Toast.makeText(ctx, er, Toast.LENGTH_LONG).show();}
else{Toast.makeText(ctx, Return, Toast.LENGTH_LONG).show();}
}
}
private void updateserver() throws IOException {
URL url = new URL(homeurl + roomurl);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("SENT:", param + " to " + url.toString());
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
inStream.close();
Return = response;
} catch (MalformedURLException ex) {
} catch (IOException ex) {
er = ex.toString();
}
return;
}
}
the code still runs fine on the old program but I made a new package and want to get that rolling... why would this happen? Thank you for taking the time!
You have a syntax error. Use
upload.send(...)
instead of
new upload.send(...)
since upload is already an instance of your class.
You should probably also make it so _upload doesn't extend AppCompatActivity (just remove the extends AppCompatActivity from public class _upload extends AppCompatActivity).

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

Android adds blank rows to db

I am trying to insert inputs to database but whenever I try, it adds empty rows to it. I have created an html form that works perfectly. Here is my code I would appreciate any help.
MyFragment.java
public class MyFragment extends Fragment{
EditText senderEt, headerEt, textEt;
Button btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.my_fragment, container, false);
senderEt = (EditText)rootView.findViewById(R.id.sender);
headerEt = (EditText)rootView.findViewById(R.id.header);
textEt = (EditText)rootView.findViewById(R.id.text);
btn = (Button) rootView.findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addToDB(getView());
}
});
return rootView;
}
public void addToDB(View view){
String sender= senderEt.getText().toString();
String header= headerEt.getText().toString();
String text= textEt.getText().toString();
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
backgroundTask.execute(sender, header, text);
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context context;
BackgroundTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String add_url= "http://139.179.196.153:8080/addDB.php";
String sender = params[0];
String header = params[1];
String text = params[2];
try {
URL url = new URL(add_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("sender", "UTF-8") + " = "+URLEncoder.encode(sender, "UTF-8")+"&"+
URLEncoder.encode("header", "UTF-8") + " = "+URLEncoder.encode(header, "UTF-8")+"&"+
URLEncoder.encode("text", "UTF-8") + " = "+URLEncoder.encode(text, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inpInputStream = httpURLConnection.getInputStream();
inpInputStream.close();
return "Add to DB Success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String res) {
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
}
}
After I debugged, I got "data" variable in "BackgroundTask" as
sender = fggff&header = kkkjjj&text = qwwqwq
do they have to be in quotes? or are the blanks problem?
php code
<?php
$db_name = "test";
$db_user = "root";
$db_password = "";
$db_server_name = "localhost";
$con = new mysqli($db_server_name, $db_user, $db_password, $db_name);
if($con->connect_error){
echo "Connection error".mysqli_connect_error();
}
else{
echo "<h3>Database connection success</h3>";
}
$sender = $_POST["sender"];
$header = $_POST["header"];
$text = $_POST["text"];
$sql_query = "insert into things values('$sender','$header','$text')";
if(mysqli_query($con, $sql_query)){
echo "<h3>Data insertion success</h3>";
}
else{
echo "<Data insertion error</h3>".mysqli_error($con);
}
Keep in mind that your background task will not do the inserts immediately when called. I think you are passing reference parameters (that is not scalars) and so the caller could be changing them before the background task has a chance to use them.
Two choices: don't do in background - for a local db, a single insert is really fast and can usually be done on the UI thread.
Or, make copies of the strings before you send them to the background task.

ImageDownload asynctask is getting start before test asynctask complted

public class DetailsActivity extends Activity {
private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;
BitmapFactory.Options bmOptions;
public class test extends AsyncTask<Void, Void, InputStream>{
ArrayList<Imageclass> str;
private DetailsActivity activity;
public test(DetailsActivity activity){
this.activity = activity;
}
#Override
protected InputStream doInBackground(Void... params) {
//String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id);
Log.e("Checking id",""+id);
String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
URL url;
try {
stringURL=stringURL.replaceAll(" ", "%20");
url = new URL(stringURL);
Log.e("URL",""+ url);
URLConnection conn= url.openConnection();
Log.e("URLConnection",""+conn );
InputStream stream= conn.getInputStream();
Log.e("URLStream",""+stream );
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("Excepiton", ""+e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Result", ""+result);
StringBuilder builder = new StringBuilder();
Log.e("Builder", ""+ builder);
BufferedReader reader = new BufferedReader(new InputStreamReader(result));
Log.e("Reader", ""+ reader);
String line = null;
try {
while((line = reader.readLine()) != null) {
Log.e("Result11", ""+ builder.append(line));
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonString = builder.toString();
Log.e("image", jsonString);
try {
JSONObject rootObject = new JSONObject(jsonString);
Log.e("JSOnObject",""+ rootObject);
JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");
//array1.clear();
ArrayList<String> imagearray = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
Imageclass imageinstance = new Imageclass();
JSONObject object = (JSONObject) jsonArray.get(index);
Log.e("Image test", "" + object);
imageinstance.image = object.getString("file_name");
//### this contain the image name
Log.e("Imageinstance.image",""+imageinstance.image);
imagename = imageinstance.image;
imagearray.add(imageinstance.image);
array1.add(imageinstance);
//array1.add(imagearray);
Log.e("array1","test"+array1);
}
Log.e("IMAGES",""+array1);
activity.setlist(array1);
}
catch (JSONException e) {
Log.e("this Exception",""+ e);
e.printStackTrace();
}
catch (Exception e) {
Log.e("NULL","NULL"+e);
}
// adapter.notifyDataSetChanged();
}
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
Log.e("inside img",""+Finalname);
Log.e("inside img_val",""+val);
Log.e("Check","check"+imageUrl);
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
Log.e("Test","Test"+ imageUrl.equals(""));
image.setImageBitmap(bm);
} else {
Toast.makeText(DetailsActivity.this,
"test", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
String Finalname;
//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
this.list= list;
Log.e("LIST",""+ this.list);
String imagename1 = list.toString();
Log.e("image new value",""+imagename1);
this.list= list;
Log.e("testing",""+ this.list);
for (int i=0; i < list.size(); i++)
{
Log.e("new check",""+list.get(i));
//String test2= list.get(i).toString();
imagetest.add(list.get(i).toString());
Finalname = list.get(i).toString();
getimage_name(Finalname);
Log.e("Come",""+list.get(i).toString());
Log.e("Finalname",""+Finalname);
}
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
private void getimage_name(String finalname2) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
image = (ImageView)findViewById(R.id.imageView2);
// getMenuInflater().inflate(R.menu.details);
//R.id.textDetailPlace
textView1 = (TextView)findViewById(R.id.textDetailPlace);
textView2 = (TextView)findViewById(R.id.textDetailAddress );
textView3 = (TextView)findViewById(R.id.textCapacity);
// textView4 = (TextView)findViewById(R.id.textDetailContactNo);
textView5 = (TextView) findViewById(R.id.textViewDescription);
textView1.setText(getIntent().getExtras().getString("test"));
textView2.setText(getIntent().getExtras().getString("test2"));
textView3.setText(getIntent().getExtras().getString("test3"));
//textView4.setText(getIntent().getExtras().getString("test4"));
textView5.setText(getIntent().getExtras().getString("test5"));
id = getIntent().getExtras().getInt("test6");
Log.e("ID value",""+id);
pid = getIntent().getExtras().getInt("test7");
Log.e("PID value",""+pid);
lati = getIntent().getExtras().getDouble("testlat");
Log.e("long",""+lati);
longi = getIntent().getExtras().getDouble("testlong");
Log.e("long",""+longi);
val=pid;
Log.e("val",""+val);
ActionBar actionBar = getActionBar();
actionBar.hide();
pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
pd.setContentView(R.layout.progress);
array1 = new ArrayList<Imageclass>();
//new test(this).execute();
new test(this).execute();
here test asynctask is called
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here imageDownload asynctask is getting called::
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
here before ImageDownload is start executing before test async task is complete
and i am not able to get the status of the task can u tell how it is done
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async.
It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed.
I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async.
An example of how to structure this is below.
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
#Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
}
Have a look here, This Help me for same..Pass your url to GetTemplateImageController and get the result in Bitmap array
GetTemplateImageController Class:
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
ServiceHandler Class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException 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 response;
}
}
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required:
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );

Failed to http Connect in Android

Well this code works fine in java but when i started to run it on Android 4.0 emulator it crashes. While Debugging i noticed that it crushed on httpConn.connect(); line
public class GetStringFromUrl {
public static String getString(String urlPageAdress) throws Exception
{
URL url = new URL(urlPageAdress);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Accept-Encoding", "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect(); //crashes on this line dunno know why
InputStream in = null;
if (httpConn.getContentEncoding() != null && httpConn.getContentEncoding().toString().contains("gzip")) {
in = new GZIPInputStream(httpConn.getInputStream());
} else {
in = httpConn.getInputStream();
}
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(1000);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);
}
String body = new String(baf.toByteArray());
return body;
} }
method is used in Main Activity
public class MainActivity extends Activity{
ToggleButton toogleButton;
public final static String EXTRA_MESSAGE = "ru.kazartsevaa.table.MESSAGE";
int upDown;
int SpinnerCount;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upDown=0;
setContentView(R.layout.activity_main);
}
public void onClick(View v) throws Exception
{ System.out.print(SpinnerCount);
// if(upDown==0) //0 - вылет 1 прилет
//{
switch (v.getId())
{
case R.id.UpDownButton:
{
//toogleButton = (ToggleButton) findViewById(R.id.UpDownButton);
// toogleButton.setOnCheckedChangeListener(this);
}
case R.id.SheremetievoButton:
{
Spinner SherSpinner = (Spinner) findViewById(R.id.SheremetievoSpinner);
String SpinnerCount= SherSpinner.getItemAtPosition(SherSpinner.getSelectedItemPosition()).toString();
System.out.print(SpinnerCount);
new Thread(){ public void run() {
try {
String body = GetStringFromUrl.getString("www.xyz.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }.start();
int crowd;
}
}
Note: After changing to new thread it stopped crushing but still writes
Are you doing this in the main thread? Should work if you execute this in a separate thread.
public void onClick(View v) {
try{
new Thread(){
public void run() {
GetStringFromUrl.getString("www.xyz.com");
}
}.start();
}catch(Exception e){
e.printStackTrace();
}
}

Categories

Resources