使asynctask运行得更快

时间:2015-03-15 11:00:04

标签: android mysql android-asynctask

我正在制作一个正在运行的聊天应用程序,但速度很慢。我需要一种方法使它更快地工作它从mysql数据库读取数据并显示它.....我正在使用asynctask ....

package com.mall.our;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;

import com.mall.first.JSONParser;
import com.mall.first.Login;
import com.mall.first.MainActivity;

import com.mall.first.R;


public class Chat extends SherlockListFragment {
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_POSTS = "posts";
    public static final String TAG_ID = "id";
    public static final String TAG_NAME = "name";
    public static final String TAG_pic = "pic";
    public static final String TAG_MESSAGE = "message";
    public static final String TAG_CATEGORIES_LOGO = "categories_logo";


  //user details
    private static final String NAME = "name";
    private static final String AGE = "age";
    private static final String STATUS = "status";
    private static final String PIC = "pic";
    private static final String SEX = "sex"; String friendname,status;

    private static final String TAG_SUCCESS = "success";
        //user
    private static final String URL = "http://www.thethinker.com.ng/ochat/chattingname.php";
    private static final String URL_CATEGORY = "http://www.thethinker.com.ng/ochat/selectchat.php";

        private BaseAdapter mAdapter;
        private ListView lv;
        SharedPreferences sp ;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.friends, container, false);
        return rootView;
    }
     @Override 
        public void onActivityCreated(Bundle savedInstanceState) {  
            super.onActivityCreated(savedInstanceState);  

            new LoadComments().execute(); 
 }

       class LoadComments extends AsyncTask<Void, Void, ArrayList<HashMap<String,String>>> {
            private ProgressDialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());

                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);

            }

            @Override
            protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {

                  ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();

                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
              String username = sp.getString("username", "anon");
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("username", username));
                  JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
                            params);

                  try {

                      JSONArray categories = json.getJSONArray(TAG_POSTS);
                      for (int i = 0; i < categories.length(); i++) {
                          String id = categories.getJSONObject(i).getString("TAG_ID");
                          String name = categories.getJSONObject(i).getString("TAG_NAME");
                          String pic = categories.getJSONObject(i).getString("TAG_pic");
                          String message = categories.getJSONObject(i).getString("TAG_MESSAGE");

                          HashMap<String, String> map = new HashMap<String, String>();
                          map.put(TAG_ID, id);
                          map.put(TAG_NAME, name);
                          map.put(TAG_pic, pic);
                          map.put(TAG_MESSAGE,message);

                          categoryList.add(map);
                      }
                  }catch (Throwable e){
                      e.printStackTrace();
                  }
                  return categoryList;
              }

            @Override
            protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
                super.onPostExecute(result);

                mAdapter = new OtherlistAdapter(getActivity(),result);
                setListAdapter(mAdapter);
                lv = getListView();
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                public void onItemClick(AdapterView<?> parent, View viewClicked,
                        final int position, long id) {


                    class loginAccess extends AsyncTask<String, String, String> {

                        protected void onPreExecute() {
                            super.onPreExecute();
                            pDialog = new ProgressDialog(getActivity());
                            pDialog.setMessage("Wait..");
                            pDialog.setIndeterminate(false);
                            pDialog.setCancelable(true);
                            pDialog.show();
                        }
                        @Override
                        protected String doInBackground(String... arg0) {

                                        int success;
                                        @SuppressWarnings("unchecked")
                                        HashMap<String, String> name = 
                                                (HashMap<String, String>) mAdapter.getItem(position);
                                        String n=name.get(TAG_NAME);


                                        try {

                                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                                            params.add(new BasicNameValuePair("username", n));


                                            Log.d("request!", "starting");

                                            JSONObject json = jsonParser.makeHttpRequest(URL, "POST",
                                                    params);

                                            Log.d("Login attempt", json.toString());

                                            String sex=json.getString(SEX);
                                            String age=json.getString(AGE);
                                            String pic=json.getString(PIC);
                                            String statuss = json.getString(STATUS);

                                            // json success tag
                                            success = json.getInt(TAG_SUCCESS);
                                            if (success == 1) {

                                                Log.d("Login Successful!", json.toString());


                                                SharedPreferences sp = PreferenceManager
                                                        .getDefaultSharedPreferences(getActivity());
                                                Editor edit = sp.edit();
                                                edit.putString("value", n);
                                                edit.putString("sex", sex);
                                                edit.putString("age", age);
                                                edit.putString("pic", pic);
                                                edit.putString("statuss", statuss);

                                                edit.commit();

                                                Intent i = new Intent(getActivity(),Chatting.class);


                                                startActivity(i);   

                                                       return json.getString(TAG_MESSAGE);
                                            } else {
                                                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                                                return json.getString(TAG_MESSAGE);
                                            }
                                        } catch (JSONException e) {

                                        }

                                        return null;

                                    }
                        protected void onPostExecute(String file_url) {
                            pDialog.dismiss();




                        }

                        }
                      new loginAccess().execute();  

                }

            });

            }
        }
    }

你可以看到第二个asynctask在第一个asynctask的postexecute中...它意味着将用户的用户名带到下一个名为&#34; CHATTING.java&#34; ...的类中。 ....一开始是点击它进入&#34; chatting.java&#34;上课有点慢........但是当我回到chat.java课程并尝试回到&#34; chatting.java&#34; ...它只是变得太慢

下面是chat.java类......

package com.mall.our;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mall.first.JSONParser;
import com.mall.first.MessageCategoryList;
import com.mall.first.R;
import com.mall.our.Chat.LoadComments;

import android.app.ListActivity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Chatting extends ListActivity {
// fr the sending of message
    private static final String TAG_POSTS = "posts";
    public static final String TAG_ID = "id";
    public static final String TAG_time = "time";
    public static final String TAG_state = "state";
    public static final String TAG_MESSAGE = "categories_message";
    public static final String TAG_CATEGORIES_LOGO = "categories_logo";
    public static final String TAG_from = "from ";
    //end


    JSONParser jsonParser = new JSONParser();
    private ProgressDialog pDialog;

    private static final String URL_CATEGORY = "http://www.thethinker.com.ng/ochat/selectmess.php";
    private static final String url = "http://www.thethinker.com.ng/ochat/sendmessage.php";
    private static final String ur = "http://www.thethinker.com.ng/ochat/seen.php";
    private BaseAdapter mAdapter;
    EditText mess;
    private ListView lv;
    ImageButton send;
    private static final String TAG_SUCCESS = "success";
    Intent b = getIntent();
    String state;
    int flag = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.yon);
        mess = (EditText) findViewById(R.id.mess);
        send = (ImageButton) findViewById(R.id.send);
        lv = getListView();
        lv.setDivider(null);

        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                    int position, long arg3) {

                Toast.makeText(Chatting.this, "Item selected: " + position,
                        Toast.LENGTH_LONG).show();

            }
        });
         final Handler ham = new Handler();
            Runnable race = new Runnable() {

                @Override
                public void run() {


                    new LoadComments().execute();

                    ham.postDelayed(this, 1 * 1000);
                }

            };
            ham.postDelayed(race, 1 * 1000);

                ff();
        sending();
    }




    private void sending() {
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {


                if (!isOnline(Chatting.this)) {
                    Toast.makeText(Chatting.this, "No network connection",
                            Toast.LENGTH_LONG).show();
                    return;
                }


                new sendtext().execute();

            }


            private boolean isOnline(Context mContext) {
                ConnectivityManager cm = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                    return true;
                }
                return false;
            }

        });

    }
    public void ff(){
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(Chatting.this);
String friendname = sp.getString("value", "anon");
String sta = sp.getString("statuss", "anon");
    TextView name = (TextView) findViewById(R.id.user);
     TextView stat = (TextView) findViewById(R.id.status);

    name.setText(friendname);
    stat.setText(sta);


}

        class LoadComments extends
            AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
        private ProgressDialog pDialog;
        int priorPosition=  getListView().getFirstVisiblePosition();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Chatting.this);

            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);

        }

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                Void... arg0) {
               int successr;

            ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();

            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(Chatting.this);
            String friend = sp.getString("value", "anon");
            String username = sp.getString("username", "anon");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("friend", friend));
            JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
                    params);


            try {

                List<NameValuePair> seen = new ArrayList<NameValuePair>();
                seen.add(new BasicNameValuePair("username", username));
                seen.add(new BasicNameValuePair("friend", friend));

                successr = json.getInt(TAG_SUCCESS);
                JSONArray categories = json.getJSONArray(TAG_POSTS);

                for (int i = 0; i < categories.length(); i++) {
                    String id = categories.getJSONObject(i).getString("TAG_ID");
                    String time = categories.getJSONObject(i).getString(
                            "TAG_time");
                    String songs_count = categories.getJSONObject(i).getString(
                            "TAG_CATEGORIES_COUNT");
                    String from = categories.getJSONObject(i).getString(
                            "TAG_from");
                state = categories.getJSONObject(i).getString(
                            "TAG_state");

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_ID, id);
                    map.put(TAG_time, time);
                    map.put(TAG_MESSAGE, songs_count);
                    map.put(TAG_from, from);
                    map.put(TAG_state, state);


                    categoryList.add(map);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return categoryList;
        }

        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            super.onPostExecute(result);


            mAdapter = new MessageCategoryList(Chatting.this,result);
            lv.setAdapter(mAdapter);
            getListView().setSelection(priorPosition);



        }
    }

    class sendtext extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Chatting.this);
            pDialog.setMessage("posting...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(Chatting.this);
            String post_username = sp.getString("username", "anon");

            String friendname = sp.getString("value", "anon");
            String picc = sp.getString("pic", "anon");
            String message = mess.getText().toString();

            params.add(new BasicNameValuePair("from", post_username));
            params.add(new BasicNameValuePair("message", message));
            params.add(new BasicNameValuePair("to", friendname));
            params.add(new BasicNameValuePair("pic", picc));

            JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
            Log.d("Create Response", json.toString());
            try {
                int success = json.getInt(TAG_SUCCESS);

            } catch (JSONException e) {
                e.printStackTrace();
            }   
            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if (flag == 1)
                Toast.makeText(Chatting.this, " saved", Toast.LENGTH_LONG)
                        .show();
            mess.setText("");
        }


      }

}

2 个答案:

答案 0 :(得分:0)

你正在尝试使用asynchrone连接的聊天应用程序,我认为它不像想法,我建议你使用WebSocket实时连接(同步连接),你可以找到许多使用websocket进行聊天的例子应用程序如下:http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ - 您需要实现服务器端 - 然后你的申请.. 我希望你喜欢这种方法

答案 1 :(得分:0)

进行以下优化:

  • 缓存经常使用的数据,因此您不必从大表中查询它
  • 将索引添加到您要搜索的字段
  • 归档旧的,很少使用的数据来归档表格
  • 确保您的查询是最佳的,并且在不增加查询复杂性的情况下合并任何可能的内容