Issues while using AsyncTask in Android Studion for Two URLs - android

I have two URLs to fetch JSON Data.
String HttpJSonURL = "https:/.......quiz.php"
String HttpJsonCatQuizURL="https://.....catquiz.php"
Now I am calling the following methods
SaveButtonInSQLite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SQLiteDataBaseBuild();
SQLiteTableQuizBuild();
SQLiteTableCatQuizBuild();
DeletePreviousData();
new StoreJSonDataInQuiz(MainActivity.this).execute();
new StoreJSonDataInCatQuiz(MainActivity.this).execute();
}
});
And the methods are defined as
private class StoreJSonDataInQuiz extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public StoreJSonDataInQuiz(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("LOADING Quiz Data");
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpJSonURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Integer catid = jsonObject.getInt("catid");
Integer id=jsonObject.getInt("_id");
String question=jsonObject.getString("question");
String answer = jsonObject.getString("answer");
String opta=jsonObject.getString("opta");
String optb=jsonObject.getString("optb");
String optc=jsonObject.getString("optc");
String optd=jsonObject.getString("optd");
String SQLiteDataBaseQueryHolder = "INSERT INTO "+SQLiteHelper.TABLE_QUIZ+"" +
" (catid,_id,question,answer,opta,optb,optc,optd) VALUES( "
+catid +", "+ id +" ,'" +question+"' "+
" ,'" +answer+"' "+
" ,'" +opta +"' "+
" ,'" +optb+"' "+
" ,'" +optc+"' "+
" ,'" +optd +"' "+
");";
sqLiteDatabase.execSQL(SQLiteDataBaseQueryHolder);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
sqLiteDatabase.close();
progressDialog.dismiss();
Toast.makeText(MainActivity.this,"Load Done", Toast.LENGTH_LONG).show();
}
}
private class StoreJSonDataInCatQuiz extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public StoreJSonDataInCatQuiz(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("LOADING CATQUIZ DATA");
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpJsonCatQuizURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Integer id=jsonObject.getInt("_id");
String quizno=jsonObject.getString("quizno");
String SQLiteDataBaseQueryHolder = "INSERT INTO "+SQLiteHelper.TABLE_CATQUIZ+"" +
" VALUES( "
+ id +" ,'" +quizno+"'); ";
sqLiteDatabase.execSQL(SQLiteDataBaseQueryHolder);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// sqLiteDatabase.close();
progressDialog.dismiss();
Toast.makeText(MainActivity.this,"Load Done", Toast.LENGTH_LONG).show();
}
}
When I write
new StoreJSonDataInQuiz(MainActivity.this).execute();
OR
new StoreJSonDataInCatQuiz(MainActivity.this).execute();
individually, it fetches data correctly.
But when both lines are executed in sequence then its not doing the job and JSON data not fetched from the 2nd URL.
Please help

Related

Get spinner data from WebService

I have created an Android application in that I am calling webservice that have attribute name and attribute value and I wants to display attribute value in Spinner and attribute name display in TextView. If attribute value is two then two arrylist is store. If attribute name is same in both list then store only one list. If attributename change then add new arraylist. Below is my code
//call webservice for product attribute
private class getCategoryProductAttribute extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ProductDescriptionActivity.this);
StringBuilder result = null;
String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("Loding..");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... strings) {
if (pref.isLoggedIn() == true) {
constant_pref.getPrefData();
} else {
constant_pref.UserName = "remplastic#admin";
constant_pref.Password = "remplastic#admin";
constant_pref.AppVersion = getVersionInfo();
constant_pref.DataVersion = "1.0";
}
Webservice addressService = new Webservice();
String query = "<value><user_name>" + constant_pref.UserName + "</user_name>" +
"<user_password>" + constant_pref.Password + "</user_password>" +
"<product_id>" + Product_Id + "</product_id>" +
"<appversion_text>" + constant_pref.AppVersion + "</appversion_text>" +
"<dataversion_text>" + constant_pref.DataVersion + "</dataversion_text></value>";
try {
addressService.XmlPostData(ConstantUrl.Product_Attribute_Url, query);
result = addressService.getResponse();
response = result.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(ConstantUrl.TAG_CODE, response));
String msg = XMLManualParser.getTagValue("message", response);
if (code == 1) {
spinnerlist.clear();
ArrayList<String> productlist = XMLManualParser.getMultipleTagList(ConstantUrl.TAG_LIST, response);
for (int i = 0; i < productlist.size(); ++i) {
String responseContent = productlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("attr_name", XMLManualParser.getTagValue(ConstantUrl.attribute_name, responseContent));
hashMap.put("attr_value", XMLManualParser.getTagValue(ConstantUrl.attribute_value, responseContent));
hashMap.put("attr_dealerprize", XMLManualParser.getTagValue(ConstantUrl.product_dealerprice, responseContent));
hashMap.put("attr_retailer_prize", XMLManualParser.getTagValue(ConstantUrl.product_retaillerprice, responseContent));
spinnerlist.add(hashMap);
if (XMLManualParser.getTagValue(ConstantUrl.attribute_name, responseContent).toLowerCase().equalsIgnoreCase("print")) {
}
}
attribute_adapter.notifyDataSetChanged();
} else {
Toast.makeText(ProductDescriptionActivity.this, msg, Toast.LENGTH_SHORT).show();
}
attribute_adapter.notifyDataSetChanged();
}
} catch (Exception e) {
}
pdLoading.dismiss();
}
}

Multiple Async Tasks one after another Android

I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.

how to refresh the ListView in android when data i appended to ListView

I have made a ListView and made a custom adapter for it,I am calling two Asynctask one for getting all messages from webservice and another is for reply of the message,I want to append the replied message to the ListView. Currently i am not getting it right way. My code is as below:
main.java
import com.epe.yehki.adapter.ChatAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class ChatHistoryActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
JSONObject jsonObj;
private ChatAdapter chatContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
Intent in;
Button reply;
RelativeLayout rl_reply;
EditText et_reply;
String url;
#Override
protected 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.activity_chat_history);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
reply = (Button) findViewById(R.id.btn_reply);
rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
rl_reply.setVisibility(View.GONE);
et_reply = (EditText) findViewById(R.id.et_reply);
menu.setSelectedTab(3);
header.title.setText("Conversation");
msgList = new ArrayList<HashMap<String, String>>();
pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");
/* new GetChatHistory().execute(); */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
rl_reply.setVisibility(View.VISIBLE);
}
});
// message reply ...!!Chat api(conversation)
reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DoReply().execute();
// new GetChatHistory().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
new GetChatHistory().execute();
}
private class GetChatHistory extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_CHAT_HISTORY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String msg_body = c.getString(Const.TAG_MESSAGE_BODY);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CUSTOMER_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_MESSAGE_BODY, msg_body);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
msgList.clear();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
System.out.println("::::::::::::inside post:::::::::::");
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
}
}
/*
* GET CONVERSATION LIST.........REPLY
*/
private class DoReply extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGE_REPLY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + et_reply.getText().toString().trim();
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString("status").equals("sucess")) {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
}
});
} else {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("::::::::::::inside post:::::::::::");
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
new GetChatHistory().execute();
}
}
}

unable to dismiss progress bar in dialogfragment

I have a dialog fragment which consists of an AsyncTask class. I am able to show a progress bar inside the dialogfragment. But unable to stop it after some time. Is there any way?
class GetStatsFromUrl extends AsyncTask<String, String, String> {
//ProgressDialogFragment pf;
ProgressBar p = null;
String info, status;
JSONObject json, json1, json2;
/*String totalquestions, notanswered,
correctanswered, wronganswered;*/
String totalquestions, notanswered,
correctanswered, wronganswered;
#SuppressLint("InlinedApi")
#Override
protected void onPreExecute() {
super.onPreExecute();
//p = new ProgressDialog(getActivity());
//p.setMessage("Loading..");
//p.setIndeterminate(true);
// p.setCancelable(false);
//p.show();
p=new ProgressBar(getActivity());
// p.setVisibility(View.VISIBLE);
//p = (ProgressBar) rootView.findViewById(R.id.loading_spinner);
//p.setVisibility(View.VISIBLE);
// p.setMax(3000 -1);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// try {
String url1 = "http://smarteach.com/questions/questions.svc/Learner_Qbank_Stats_Today/val1="
+ learnerid
+ "/val2="
+ courseid
+ "/val3="
+ session_id + "";
System.out.println("Stats from URL : " + url1);
ServiceHandler sh = new ServiceHandler();
jsonstring = sh.makeServiceCall(url1, ServiceHandler.GET);
System.out.println("Response: " + jsonstring);
if (jsonstring != null && jsonstring.length() > 0) {
try {
JSONObject questionsObject = new JSONObject(jsonstring);
JSONArray questionsArray = questionsObject
.getJSONArray("Table");
if (questionsArray != null && questionsArray.length() > 0) {
for (int i = 0; i < questionsArray.length(); i++) {
JSONObject innerQuestionObject = (JSONObject) questionsArray
.get(i);
String count = innerQuestionObject.getString("Count");
String result = innerQuestionObject.getString("Result");
if (result.equalsIgnoreCase("R")) {
correctanswered = count;
} else if (result.equalsIgnoreCase("Total Questions")) {
totalquestions = count;
} else if(result.equalsIgnoreCase("W")){
// notanswered = count;
wronganswered = count;
}
/* if(result.equalsIgnoreCase("W")){
wronganswered = count;
}*/
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getActivity(), "Please try after some time",
Toast.LENGTH_LONG).show();
}
return url1;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//p.dismiss();
// TODO Auto-generated method stub
System.out.println("In onpostexecute status");
// p.setVisibility(View.GONE);
tvbookmarkcount.setText(totalquestions);
//tvquesunattempted.setText(notanswered);
tvcorrectanswered.setText(correctanswered);
tvwronganswered.setText(wronganswered);
}
}
try below code:-
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
p.dismiss();
}
you must call dismiss when your task is complete (onPostExecute).

how to show list of suggestion in AutoCompleteTextView and fill data from api

AutoCompleteTextView doesn't show any suggestions but data is filled in the adapter
Here is my block of CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
/* param.add(new BasicNameValuePair("catId", id));
param.add(new BasicNameValuePair("level", level));*/
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
ArrayList<String>sug_list=new ArrayList<String>();
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
//Toast.makeText(getBaseContext(), item.toString(), Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(Home.this,android.R.layout.simple_dropdown_item_1line, item);
// Create adapter
//adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, item);
autocomplete.setThreshold(1);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
While debugging it is showing the words
GUYS help me please :'(
As suggested by other guys here this is the changes i have done
MODIFIED CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,sug_list);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(),sug_list+"",Toast.LENGTH_LONG).show();
}
}
Here is the item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#eaeaea"
android:padding="10dp"
android:textColor="#000"
android:textSize="16sp" >
</TextView>
After spending 6 hours I come to know that I have to add one line
autocomplete.showDropDown();
in onpost of async
check this page
you may need to update the UI.
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});

Categories

Resources