我想从asynctask使用UIL.
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class SingleAppDetail extends Activity {
Button btnLogout;
Button btShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
JSONparser jParser = new JSONparser();
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
private static String file_url = "http://site.com/as.apk";
JSONArray detalii = null;
TextView app_Detail_title;
Button app_price_button;
TextView app_Description;
ImageView app_Picture;
View loadingPanelViev;
View appDetailHeader;
RatingBar appDetailRating;
RatingBar rating_1;
RatingBar rating_2;
RatingBar rating_3;
RatingBar rating_4;
RatingBar rating_5;
RatingBar rating_ff;
TextView …Run Code Online (Sandbox Code Playgroud) 我是android的新手,我试图从服务器获取一些数据并将其打印在我的设备中.我意识到使用android 4.x我们无法做到这一点因为UI线程被阻止了.我进行了研究,发现了AsyncTask.有人可以帮我一些代码吗?有什么遗失的吗?谢谢
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread().execute();
openDialog(getCurrentFocus());
}
Run Code Online (Sandbox Code Playgroud)
AsynTask类:
private class Thread extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//Here i make a HTTP request.
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
logcat的:
04-22 22:43:10.808: E/Trace(12987): error opening trace file: No such file or directory (2)
04-22 22:43:11.098: E/AndroidRuntime(12987): FATAL EXCEPTION: AsyncTask #1
04-22 22:43:11.098: E/AndroidRuntime(12987): java.lang.RuntimeException: An error occured while executing doInBackground()
04-22 22:43:11.098: E/AndroidRuntime(12987): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-22 22:43:11.098: E/AndroidRuntime(12987): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) …Run Code Online (Sandbox Code Playgroud) 我正在获取响应并解析数据并存储在String现在我要在Edittext中显示我正在获得以下异常.我正在获取响应并在AsyncTask中解析
05-02 10:13:56.797: W/System.err(17935): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-02 10:13:56.867: W/System.err(17935): at android.view.ViewRoot.checkThread(ViewRoot.java:2812)
05-02 10:13:56.867: W/System.err(17935): at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
05-02 10:13:56.867: W/System.err(17935): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
05-02 10:13:56.867: W/System.err(17935): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
05-02 10:13:56.867: W/System.err(17935): at android.view.View.invalidate(View.java:5115)
05-02 10:13:56.867: W/System.err(17935): at android.widget.TextView.invalidateCursor(TextView.java:3661)
05-02 10:13:56.867: W/System.err(17935): at android.widget.TextView.spanChange(TextView.java:6352)
05-02 10:13:56.867: W/System.err(17935): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:6477)
05-02 10:13:56.867: W/System.err(17935): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:906)
05-02 10:13:56.867: W/System.err(17935): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:611)
05-02 10:13:56.867: W/System.err(17935): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:514)
05-02 10:13:56.867: W/System.err(17935): at android.text.Selection.setSelection(Selection.java:74)
05-02 10:13:56.867: …Run Code Online (Sandbox Code Playgroud) 我有一个自定义ListAdapter,它在AsyncTask中从Internet获取数据.
数据完全添加到列表中,但是当我尝试执行操作时,应用程序崩溃了......
我确定这是因为我正在调用notifyDataSetChanged(); 在错误的时间(即在AsyncTask结束之前).
我现在得到了什么:
public class MyListAdapter extends BaseAdapter {
private ArrayList<String> mStrings = new ArrayList<String>();
public MyListAdapter() {
new RetreiveStringsTask().execute(internet_url);
//here I call the notify function ****************
this.notifyDataSetChanged();
}
class RetreiveStringsTask extends AsyncTask<String, Void, ArrayList<String>> {
private Exception exception;
@Override
protected ArrayList<String> doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
//return arraylist
return getStringsFromInternet(url);;
} catch (Exception e) {
this.exception = e;
Log.e("AsyncTask", exception.toString());
return null;
}
}
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours …Run Code Online (Sandbox Code Playgroud) 我无法在AsyncTask中创建对话框.有人可以帮忙吗?我收到错误"android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序".
这是我的代码:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTaskTest at=new AsyncTaskTest();
at.execute();
}
public class AsyncTaskTest extends AsyncTask<Void, String, Void> {
protected Void doInBackground(Void... vd){
try{
String desc = "Show Dialog without error";
publishProgress(desc);
}catch(Exception e){
publishProgress("Error: "+e.toString());
}
return null;
}
protected void onProgressUpdate(String... msg) {
showDialog(msg[0]);
}
private void showDialog(String msg){
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(getApplicationContext(), android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface …Run Code Online (Sandbox Code Playgroud) 我有片段,我在每个片段中缓存数据.我通过从服务器下载doInBackground方法将数据缓存在AsyncTask中,并将其保存在onPostExecute中保存到我的数据库中.所以我总是在onPostExecution中打开数据库连接.如果我滚动"快速"扔掉片段,我认为AsyncTasks通过了预览实例,并且android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)在行中会有一个,我在那里打开连接(获取dbHelper.getWritableDatabase())
我认为有两种方法可以解决这个问题:
onPostExecution方法必须等到预览AsyncTask(onPostExecution)完成
有一种方法可以为AsyncTask的所有实例使用相同的数据库连接,而无需相互锁定它们
它是否正确?有人有点想法,怎么做?
首先,关于我的项目的一些信息:
我有一个由几个片段组成的应用程序.(我有一个扩展FragmentActivity的类和另一个扩展FragmentPagerAdapter的类.)所以实际上我的代码在Fragments中运行.
我在其中一个片段中调用了一个asynctask进行一些计算.asyncTask是一个单独的文件,该类不在Fragment类中.
因此,1个文件是asynctask,另一个是fragmet(来自片段的变量不能直接由asynctask访问!!!).
我可以使用ProgressDialog显示asyncTask的结果.但是我希望能够将数据(asynctask的结果)返回给我片段中的变量.到目前为止我尝试过的是:
我试着这样做:
我使用了以下按钮单击后调用的代码.
mytask1 = new myAsyncTask(this);
String result =mytask1.execute(value1).get();
Run Code Online (Sandbox Code Playgroud)
但是这会导致主线程卡住并等待asynctask完成.
2.使用loginSharePreferens
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
loginPrefsEditor.putString("result", result);
loginPrefsEditor.commit();
Run Code Online (Sandbox Code Playgroud)
这给了我错误.
我也试过这个
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext() );
这与第二种方法类似.
4.我试图在我的片段中创建一个只设置值的方法,我试图在片段内调用它
MyFrragment1.this.setRestult(1); // is called in the onPostExecute of the asyncTask
public void setRestult(int result){
this.test1=result; ///inside of the fragment
}
Run Code Online (Sandbox Code Playgroud)
这给了我错误:"在范围内无法访问MyFragment1类型的封闭实例"
我不知道还有什么可以尝试的.有任何想法吗 ?
我需要从服务器下载一个文本文件,然后将其保存在内存中.然后一行一行地阅读.更好的关闭 - 直接从服务器逐行读取.
编辑:'将其保存在内存中'意味着不将其写入文件.
你会怎么做?
谢谢!
我试图让我的操作栏完成对api的搜索并解析json结果.
我把asycTask放在一起像这样:
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
///get
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherObservationItems =
new JSONObject(jsonObject.getString("JSON"));
Toast.makeText(getBaseContext(),
weatherObservationItems.getString("totalResults"),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
//gets the json from the inputed url
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse …Run Code Online (Sandbox Code Playgroud) 我正在调用soap webservice并需要显示返回的内容.但我不能这样做,因为AsyncTask很复杂,我不知道如何正确使用它.你能告诉我如何通过asynctask从被调用函数返回数据吗?
这是我的代码
public class WebserviceTool {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.168.0.11:9289/Service1.asmx";
private final String SOAP_ACTION = "http://tempuri.org/get_currency";
private final String METHOD_NAME = "get_currency";
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String execute_barcode_webservice(String s1, String s2) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("date",s1);
request.addProperty("cur_code",s2);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.encodingStyle = SoapEnvelope.ENC;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Object …Run Code Online (Sandbox Code Playgroud) android ×10
java ×2
json ×2
baseadapter ×1
image ×1
listadapter ×1
loader ×1
locking ×1
universal ×1
web-services ×1