0

嗨,这是我的第一个应用程序。在编程和 android 方面,我是初学者。我的应用程序类似于 twitter 应用程序。但是,它不会从 twitter 获取值,而是从我的数据库中获取值。该应用程序将加载图像和网页链接。

我的问题。假设我的应用在应用商店中并且有人下载了它。我的应用程序通过 Json 从我的 mysql 数据库中获取大部分内容。每次我向数据库添加新内容时,用户必须更新应用程序以获取新内容,否则它会自动更新自身。

有人可以看看我的代码。我不确定 Async() 和 doInBackground()。如果您有任何其他有用的编码建议,请告诉我。我想在完成后将此应用程序放在应用程序商店中。

亲切的问候

public class TwitterFeedActivity extends ListActivity {

    private ArrayList<Tweet> tweets = new ArrayList<Tweet>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyTask().execute();
    }
    private class MyTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progressDialog;


        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(TwitterFeedActivity.this,
                    "", "Loading. Please wait...", true);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                HttpClient hc = new DefaultHttpClient();
                HttpGet get = new HttpGet("http://myurl.com");
                HttpResponse rp = hc.execute(get);

                if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    String result = EntityUtils.toString(rp.getEntity());
                    JSONObject root = new JSONObject(result);
                    JSONArray sessions = root.getJSONArray("results");

                    for (int i = 0; i < sessions.length(); i++) {
                        JSONObject session = sessions.getJSONObject(i);
                        Tweet tweet = new Tweet();
                        tweet.n_text = session.getString("n_text");
                        tweet.n_name = session.getString("n_name");
                        tweet.Image = session.getString("Image");
                        tweets.add(tweet);
                    }
                }

            } catch (Exception e) {
                Log.e("TwitterFeedActivity", "Error loading JSON", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            progressDialog.dismiss();
            setListAdapter(new TweetListAdaptor(TwitterFeedActivity.this, R.layout.list_item, tweets));
        }
    }

    private class TweetListAdaptor extends ArrayAdapter<Tweet> {
        private ArrayList<Tweet> tweets;
        public TweetListAdaptor(Context context, int textViewResourceId, ArrayList<Tweet> items) {
            super(context, textViewResourceId, items);
            this.tweets = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list_item, null);
            }
            final Tweet o = tweets.get(position);
            TextView tt = (TextView) v.findViewById(R.id.toptext);
            TextView bt = (TextView) v.findViewById(R.id.bottomtext);
            ImageView image = (ImageView) v.findViewById(R.id.avatar);
            bt.setText(o.n_name);
            tt.setText(o.n_text);
            image.setImageBitmap(getBitmap(o.Image));

            image.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v){
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse(o.n_text));
                    startActivity(intent);
                }
            });

            return v;
        }
    }

    public Bitmap getBitmap(String bitmapUrl) {
        try {
            URL url = new URL(bitmapUrl);
            return BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
        }
        catch(Exception ex) {return null;}
    }
}
4

1 回答 1

0

好的,我正在发布与异步相关的代码。我希望,你会发现它有帮助。首先,创建一个类,如下所示:

package com.example.pre;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;




import android.util.Log;

public class JSONFunctions {

    public String CreateCon(String url){
        String res="";
        try{
            URL u=new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.
                    openConnection();

                res=readStream(con.getInputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       




        return res;
    }

    private String readStream(InputStream is) {
        // TODO Auto-generated method stub
        String result = "";
        BufferedReader reader=null;
          try{
                reader = new BufferedReader(new InputStreamReader(is));

                String line = null;
                while ((line = reader.readLine()) != null) {
                        result=result+line;
                }
          }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }finally{
            if(reader!=null)
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

在你的主类中,粘贴以下方法:

 private class PostTask extends AsyncTask<String, Integer, String>{

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        readJson();
            //progress_dialog.dismiss();
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        JSONFunctions jsonf=new JSONFunctions();
        str1=jsonf.CreateCon(cat_url);
        return null;
    }
}

其中 readJson 是您定义功能的方法,而 str1 是您提供 json 地址的字符串。不要忘记调用 PostExecute 类。

于 2012-12-22T06:03:07.403 回答