/ / spraw, aby asynctask działał szybciej - android, mysql, android-asynctask

spraw, aby asynktask działał szybciej - android, mysql, android-asynctask

tworzę aplikację do czatu, działa, ale jest powolna. Potrzebuję sposobu, aby przyspieszyć działanie Czyta dane z bazy danych MySQL i wyświetla je ..... i używam 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();

}

});

}
}
}

jak widać, druga asynctask znajduje się wpostexecute pierwszego asynctask ... ma na celu przeniesienie nazwy użytkownika do następnej klasy o nazwie „CHATTING.java” ....... na początku, kiedy kliknie, przechodzi do klasy „chatting.java” trochę powoli ........ ale kiedy wracam do klasy chat.java i próbuję wrócić do "chatting.java" ... po prostu robi się zbyt wolno

Poniżej znajduje się klasa chatting.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("");
}


}

}

Odpowiedzi:

0 dla odpowiedzi № 1

próbujesz aplikacji czatu z asynchronepołączenie, myślę, że to nie jest dobry pomysł, radzę korzystać z WebSocket do połączenia w czasie rzeczywistym (połączenie synchroniczne), możesz znaleźć wiele przykładów, które używają websocket do czatu w następujący sposób: http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ - potrzebujesz implementacji po stronie serwera - następnie Twoja aplikacja .. Mam nadzieję, że podoba Ci się to podejście


0 dla odpowiedzi nr 2

Dokonaj następujących optymalizacji:

  • buforuj często używane dane, więc nie musisz wyszukiwać ich z dużej tabeli
  • dodaj indeksy do pól, których szukasz
  • archiwizuj stare, rzadko używane dane do archiwizacji tabel
  • upewnij się, że Twoje zapytania są optymalne i że scalasz wszystko, co jest możliwe, bez zwiększania złożoności swoich zapytań