/ / make asynctask courir plus vite - android, mysql, android-asynctask

faire asynctask courir plus vite - android, mysql, android-asynctask

Je fais une application de chat ça marche mais c'est lent. J'ai besoin d'un moyen de le faire fonctionner plus rapidement, il lit les données de la base de données mysql et les affiche ..... et j'utilise 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();

}

});

}
}
}

comme vous pouvez le voir, le deuxième asyncte est danspostexecute du premier asyncte ... il est censé prendre le nom d'utilisateur de l'utilisateur dans la classe suivante appelée "CHATTING.java" ... au début, cliquez dessus pour passer à la classe "chatting.java" un peu lentement ........ mais quand je retourne à la classe chat.java et que j'essaie de revenir à "chatting.java" ... ça devient trop lent

Ci-dessous, la classe 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("");
}


}

}

Réponses:

0 pour la réponse № 1

vous essayez une application de chat avec asynchroneconnexion, je pense que ce n’est pas une bonne idée, je vous conseille d’utiliser WebSocket pour une connexion en temps réel (connexion synchrone). http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ - vous devez implémenter un serveur - ensuite votre application .. J'espère que vous aimez cette approche


0 pour la réponse № 2

Effectuez les optimisations suivantes:

  • met en cache les données fréquemment utilisées, vous n'avez donc pas à les interroger à partir d'une grande table
  • ajouter des index aux champs que vous recherchez
  • archive des données anciennes, rarement utilisées, pour archiver des tables
  • assurez-vous que vos requêtes sont optimales et que vous fusionnez tout ce qui est possible sans augmenter la complexité de vos requêtes