AutoCompleteTextView Via XMLParsing onTextChange - java

I have this problem. I need to send a call to my SAX Parser (every time user tries enter name of the student) to get the names. What I am doing right now is sending a token-string to my HttpHandler which is returning 10 records every time because total no of students are about 40K so I can't parse them all at once. I am calling my AsyncTask for ParsingXML in onTextChanged event of AutoCompletetextview. but still I am not able to set the adapter to Autocomplete.
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL(xyz.com/xyz.ashx?token=+"token"); // URL of the XML
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
Here is my AutoCompleteTextViewAdapter Code
ArrayList<AutoCompleteUserDataGetterSetter> data=new ArrayList<AutoCompleteUserDataGetterSetter>();
public UserNewMessageAutoCompleteAdapater(Context context,
int textViewResourceId,
ArrayList<AutoCompleteUserDataGetterSetter>data) {
super(context, textViewResourceId, data);
// TODO Auto-generated constructor stub
this.context = context;
this.data=data;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final AutoCompleteUserDataGetterSetter i = this.data.get(position);
if (i != null) {
Log.d("adapter", "in here");
AutoCompleteUserDataGetterSetter si = (AutoCompleteUserDataGetterSetter) i;
v = vi.inflate(R.layout.autocompletetext_layout, null);
final TextView title = (TextView) v
.findViewById(R.id.autocomplete_name);
TextView userid = (TextView) v
.findViewById(R.id.autocompleteuserid);
if (title != null)
title.setText(si.GetFullName());
userid.setText(si.GetUserId());
}
return v;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public AutoCompleteUserDataGetterSetter getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
and here is my AsyncTask Class
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
for(int i=0;i<data.size();i++)
{
nameadapter.add(data.get(i).GetFullName());
useridadapter.add(data.get(i).GetUserId());
}
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
users.setAdapter(nameadapter);
}
}

Finally after some head-desking finally sorted the issue Finally!
I gave up the custom adapter approach and used the ArrayAdapter approach. so here is the complete code for my Sending Messages to users via selecting their names.
public class UserMessagesComposeNewActivity extends Activity implements TextWatcher{
ArrayList<AutoCompleteUserDataGetterSetter> data=new
ArrayList<AutoCompleteUserDataGetterSetter>();
Long login;
Boolean shouldAutoComplete;
UserNewMessageAutoCompleteAdapater cdapater;
String TO,FROM;
Button btn;
AutoCompleteTextView users;
EditText edTextSubject,edTextMessage;
AutoCompleteWidget myAutoComplete;
List<String> nameadapter=new ArrayList<String>();
ArrayAdapter<String> dataAdapter ;
UserNewMessageAutoCompleteAdapater atAdapter;
String ResultEmail;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
setContentView(R.layout.user_messages_compose_new);
login=intent.getLongExtra("EmployeedId", 0);
btn=(Button)findViewById(R.id.userNewmessageSendButton);
edTextSubject=(EditText)findViewById(R.id.userNewmessageSubject);
edTextMessage=(EditText)findViewById(R.id.userNewmessageMessage);
users=(AutoCompleteTextView)findViewById(R.id.userNewmessageAutoCT);
users.addTextChangedListener(this);
users.setThreshold(4);
//Here we get the selected value from autocompletetextview dropdown
users.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for(int i=0;i<data.size();i++)
{
if(data.get(i).GetFullName().equals(users.getText().toString()))
{
TO=data.get(i).GetUserId();
}
else
{
TO="0";
}
}
}
});
//here we call the Send Email method.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DomParserEmail().execute();
}
});
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>=4)
{
new SomeTask().execute();
}
}
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
//Here we are parsing the xml
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
UserMessagesComposeNewActivity.this.nameadapter.clear();
for(int i=0;i<data.size();i++)
{
UserMessagesComposeNewActivity.this.nameadapter.add(UserMessagesComposeNewActivity.this.data.get(i).GetFullName());
}
dataAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, nameadapter);
dataAdapter.notifyDataSetChanged();
users.setAdapter(dataAdapter);
users.showDropDown();
}
}
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("blah blah"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
class DomParserEmail extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Sending your message");
this.dialog.setTitle("Please Wait");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// download and parse
UserMessagesComposeNewActivity.this.ResultEmail=EmailSuccessMessage(UserMessagesComposeNewActivity.this.edTextSubject.getText().toString(),UserMessagesComposeNewActivity.this.edTextMessage.getText().toString(),UserMessagesComposeNewActivity.this.TO,UserMessagesComposeNewActivity.this.login.toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
Toast toast=Toast.makeText(getApplicationContext(),UserMessagesComposeNewActivity.this.ResultEmail,Toast.LENGTH_LONG );
toast.show();
}
}
}
public String EmailSuccessMessage(String subject,String content,String To, String From) throws FactoryConfigurationError
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("abc.com/abc.asahx?blah blah");
/**
* Create the Handler to handle each of the XML tags.
**/
UserReplyMessageXMLParsing myXMLHandler = new UserReplyMessageXMLParsing();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
}
catch (Exception e)
{
System.out.println(e);
UserMessagesComposeNewActivity.this.ResultEmail="Email Not Sent";
}
UserReplyMessageXMLParsing usmx=new UserReplyMessageXMLParsing();
UserMessagesComposeNewActivity.this.ResultEmail=usmx.GetEmailStatus();
return UserMessagesComposeNewActivity.this.ResultEmail;
}
}

Related

Recycleview's onClick and put extra

Please help! i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!
this my code , somebody tell my wrongs:):
AdapterFish.java
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ID");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
and Searching.java
public class searching extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searching);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(searching.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.company = json_data.getString("company");
fishData.name = json_data.getString("name");
fishData.family = json_data.getString("family");
fishData.id = json_data.getString("id");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(searching.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Try this
#Override
public void onClick(View v) {
DataFish newCurrent=data.get(getAdapterPosition());
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = newCurrent.id;
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
hopefully this will work .. but what exactly is your problem ? is it detecting the clicked value or passing ID to new Activity?
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.setTag(current); //<--added
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
DataFish clickedData = (DataFish) v.getTag(); //<-- pull data from tag
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", clickedData.id);
context.startActivity(intent);
}
});
}
Try with following code hope so it will be working.
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
//final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", current.id);
context.startActivity(intent);
}
});
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getExtra("ID");
System.out.println("TempItem=============>"+TempItem )
//Calling method to filter Student Record and open selected record.
if(null != TempItem){
HttpWebCall(TempItem);
}else{
Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
}
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
Replace this line in ShowSingleRecordActivity
TempItem = getIntent().getStringExtra("ID");
to
TempItem = getIntent().getExtras().getString("ID");

How to add asyncTask code in application?

I have a register activity in my application. This has inputs of userid,email,password and mobile no. I have created an UI.
code:
public class RegisterActivity extends AppCompatActivity {
TextView already;
Button signUp;
RelativeLayout parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
parent = (RelativeLayout)findViewById(R.id.parentPanel);
setupUI(parent);
already = (TextView)findViewById(R.id.alreadyRegistered);
signUp = (Button) findViewById(R.id.sign_up_button);
already.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(RegisterActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
Now I want to sync this UI with server.
For this I have a code of asyncTask created in another activity. How can I call this code or implement this code with UI?
AsyncTask code : RegisterActivity
public class RegisterActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = this;
RegisterAsyncTask task = new RegisterAsyncTask();
String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
}
public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("result");
String message = jsonObject.getString("message");
if ( result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code when api fails goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
How can I sync this? Please help. Thank you.
EDIT:
getEventsAsyncTask:
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog :
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog want to show events from asyncTask. Thank you.
Not sure if i understand your question correctly, but to execute the AsyncTask, you just have to create an instance of RegisterAsyncTask and call the execute() method on it.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method
Or, if you don't need to get ahold of the instance:
new RegisterAsyncTask().execute(yourMap);
You can simply put your hashmap object, alongwith AsyncTask in your login activity code, and simply call AsyncTask in following manner.
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(params);

how to make a service for locking applications in android?

I am making an Android application to lock applications.
I have selected the applications I want to lock and saved them in SharedPreferences, but I don't know how to make the service which will detect every application which will be launched on the mobile and compare that package name with the package names saved in SharedPreferences and display my lock activity instead of that application.
This is the code I have written in my service.
public class DetectorService extends Service {
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
String foregroundTaskPackageName;
RunningTaskInfo foregroundTaskInfo;
try {
Thread.sleep(100);
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
foregroundTaskInfo = am.getRunningTasks(1).get(0);
foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
PackageManager pm = getBaseContext().getPackageManager();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
String[] abc = AppLockerPreference.getInstance(getApplicationContext()).getApplicationList();
for(int i = 0 ; i < abc.length ; i++)
{
if(abc[i].equals(foregroundTaskInfo.topActivity.getPackageName().toString()))
{
Intent lockIntent = new Intent(getApplicationContext(), GalleryImages.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(lockIntent);
}
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And this is my code where I select the applications and save them in SharedPreferences. I am starting the service onPause method of this code.
public class AllAppsActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
AppLockerPreference ap;
String prefApps[];
boolean[] appflag;
int[] arr;
int count = 0;
ImageView ivlock;
Button bloc;
ListView mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ap = new AppLockerPreference(getApplicationContext());
packageManager = getPackageManager();
new LoadApplications().execute();
mylist = getListView();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
startService(new Intent(this, DetectorService.class));
//Toast.makeText(AllAppsActivity.this, sc.getString("app_loc", ""), Toast.LENGTH_SHORT).show();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ivlock = (ImageView) v.findViewById(R.id.app_lockimg);
if (ivlock.getDrawable() != null) {
ivlock.setImageDrawable(null);
appflag[position] = false;
} else {
ivlock.setImageResource(R.drawable.ic_action_secure);
appflag[position] = true;
}
for (int i = 0; i < appflag.length; ++i) {
if (appflag[i] == true) {
count++;
}
}
arr = new int[count];
int a = 0;
for (int i = 0; i < appflag.length; ++i) {
if (appflag[i] == true) {
arr[a] = i;
a++;
}
}
String[] prefapps = new String[count];
for (int i = 0; i < count; ++i) {
ApplicationInfo data = applist.get(arr[i]);
prefapps[i] = data.packageName.toString();
}
ap.saveCount(count);
ap.saveApplicationList(prefapps);
ap.saveServiceEnabled(true);
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(AllAppsActivity.this, R.layout.snippet_list_row, applist);
appflag = new boolean[listadaptor.getCount()];
for (int i = 0; i < listadaptor.getCount(); i++) {
appflag[i] = false;
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(AllAppsActivity.this, null, "Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public ApplicationAdapter(Context context, int textViewResourceId, List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
}
ApplicationInfo data = appsList.get(position);
TextView appName = (TextView) view.findViewById(R.id.app_name);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
ImageView lockimg = (ImageView) view.findViewById(R.id.app_lockimg);
String[] prefapps;
prefapps = ap.getApplicationList();
//prefapps = new String[counter];
boolean flag = false;
String label = (String) data.packageName;
for(int i=0;i<prefapps.length;++i)
{
if(prefapps[i].equals(label))
{
flag = true;
//Toast.makeText(AllAppsActivity.this, ddd, Toast.LENGTH_SHORT).show();
}
}
if(flag==true)
{
lockimg.setImageResource(R.drawable.ic_action_secure);
appflag[position]=true;
appName.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
}
else
{
lockimg.setImageDrawable(null);
appflag[position] = false;
appName.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
}
}
I tried on my own and found a way to make the service. Here is the code.
public class DetectorService extends Service {
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
final boolean running = true;
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ActivityManager mActivityManager = (ActivityManager) getSystemService(getApplicationContext().ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
String[] prefs;
AppLockerPreference ap = new AppLockerPreference(getApplicationContext());
prefs = ap.getApplicationList();
for(int i = 0; i < prefs.length ; i++)
{
for(int j = 0; j< RunningTask.size() ; j++)
{
ActivityManager.RunningTaskInfo ar = RunningTask.get(j);
String activityOnTop=ar.topActivity.getPackageName();
if(prefs[i].equals(activityOnTop))
{
Intent lockIntent = new Intent(getApplicationContext(), GalleryImages.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(lockIntent);
}
}
}
}
}
}
).start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Remove notification from status bar after 20 second in android?

I created an android application. In this application I use the push notification concept. The notification is sent and received properly on the receiver.
Now I want to display the notification on status bar only for 20 second after that it will disappear. Can anyone tell me how can I do this? This is what I´ve so far.
public class ViewRecievedJobs extends Activity {
//private Button accept,reject;
private SharedPreferences pref;
private String login_token;
int status;
FragmentSendJob fsj;
ListView list;
Context con;
int pos;
static String job_id;
DatabaseAdmin database ;
ArrayList<HashMap<String, String>> adsArray = new ArrayList<HashMap<String,String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_received_jobs);
con=this;
pref=this.getSharedPreferences("Driver", MODE_WORLD_READABLE);
login_token = pref.getString("login_token","login_token");
database = new DatabaseAdmin(getApplicationContext());
//adsArray = database.getRecords_ads("Select * from SUN_NOTI where received =0");
//
//fsj.job_id=id;
//Log.e("adsArray", ""+adsArray);
list=(ListView)findViewById(R.id.listView1);
}
#Override
protected void onResume()
{
// Log.e("onResume", "onResume");
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
list.setAdapter(new ReceivedJobList());
super.onResume();
}
class ReceivedJobList extends BaseAdapter
{
public int getCount() {
// TODO Auto-generated method stub
return adsArray.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return adsArray.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int arg0, View cView, ViewGroup arg2)
{
pos=arg0;
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cView = inflater.inflate(R.layout.job_received, null);
TextView name = (TextView)cView.findViewById(R.id.esuburb);
TextView dest = (TextView)cView.findViewById(R.id.edestination);
name.setText(adsArray.get(arg0).get("suburb"));
dest.setText(adsArray.get(arg0).get("destination"));
// Button view = (Button) cView.findViewById(R.id.view);
Button accept = (Button) cView.findViewById(R.id.accept);
Button reject = (Button) cView.findViewById(R.id.reject);
accept.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=0;
job_id=adsArray.get(arg0).get("message_id");
new JobStatus().execute();
// new ViewAdvertisement().execute();
// Toast.makeText(LoginScreen.this, "You clicked the button", Toast.LENGTH_SHORT).show();
}
});
/* view.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "view");
i.putExtra("array",adsArray );
startActivity(i);
}
});*/
reject.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=2;
new JobStatus().execute();
}
});
return cView;
}
}
private class JobStatus extends AsyncTask<String, String, String[]> {
private ProgressDialog dialog;
protected void onPreExecute()
{
dialog = ProgressDialog.show(ViewRecievedJobs.this, "", "");
dialog.setContentView(R.layout.main);
dialog.show();
}
#Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
JSONObject job1= new JSONObject();
try
{
job1.put("status_key",status);
job1.put("method", "job_status");
job1.put("login_token", login_token);
//job1.put("status",status);
job1.put("job_id",job_id);
StringEntity se = new StringEntity(job1.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/DGCapp/webservice.php");
httppost.setEntity(se);
HttpResponse response1 = httpclient.execute(httppost);
String data1 = EntityUtils.toString(response1.getEntity());
Log.e("response",""+data1);
JSONObject jo = new JSONObject(data1);
String err=jo.getString("err-code");
if(err.equals("0"))
{
if( status == 0)
{
database.update_data(adsArray.get(pos).get("message_id"),"2");
//Toast.makeText(con, "Job Accepted", Toast.LENGTH_SHORT).show();
//show_Toast("Job Accepted");
dialog.dismiss();
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "accept");
i.putExtra("array",adsArray );
startActivity(i);
}
else
{
database.delete_data(adsArray.get(pos).get("message_id"));
//show_Toast("Job Rejected");
//Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(ViewRecievedJobs.this);
alert.setTitle("Alert !");
alert.setMessage("No Internet connection ");
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,
int whichButton)
{
dialog.dismiss();
dialog2.dismiss();
}
});
runOnUiThread(new Runnable()
{
public void run()
{
//pDialog.dismiss();
alert.show();
}
});
}
return params;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
if(dialog.isShowing())
{
dialog.dismiss();
}
if(status == 2)
{
Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
list.setAdapter(new ReceivedJobList());
}
}
/*public void show_Toast(String msg)
{
Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
}*/
}
}
you can create a service that runs in the background and that will timeout after 20 minutes and delete your notification.Before that a notification should be there to notify the user... and the user should be able to dismiss it on their own.
Reference :
Make notification disappear after 5 minutes

Creating Progress dialog while switching from one activity to another

I have a custom DialogFragment. I want to show this dialog while switching my activities.
Scenario:-
1) In actvity1 I start the dialog.
2) Start a asynctask class.
3) Do some authentication in doInBackground().
4) Start new actvity from onPostExecute().
Issue:-
The dialog stops before the asynctask.
Here is my code:-
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon)
{
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
redirected =view.getUrl();
redirected= Uri.decode(redirected);
if(redirected!=null && redirected.contains(string1))
{
myprogressDialog.show(getFragmentManager(), "Wait");
}
}
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(redirected!=null && redirected.contains(mystring) )
{
myWebView.stopLoading();
String authorizationContentString = myurl
new Authentication(Activity2.this, myprogressDialog, url).execute(authorizationString);
}
private static class ProgressDialogFragment extends DialogFragment
{
public static ProgressDialogFragment newInstance()
{
return new ProgressDialogFragment();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_dialog_progress, container, false);
}
}
Authentication.java
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
/* progDia.show(man, "wait");
progDia= new Utility.ProgressDialogFragment().newInstance();*/
}
public AuthenticateDevice(Details1 myContext, ProgressDialogFragment myprogressDialog, String Url)
{
// TODO Auto-generated constructor stub
mContext = myContext;
this.progDia = myprogressDialog;
this.Url = Url;
this.mActivity = myContext;
}
#Override
protected Void doInBackground(String... params)
{
// TODO Auto-generated method stub
//Some authentication
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progDia!=null&&progDia.isVisible())
{
progDia.dismiss();
}
Intent myIntent = new Intent(mContext, Activity2.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(myIntent);
mActivity.finish();
}
Try following code to show progress dialog in async
ProgressDialog pd;
class MYAsync extends AsyncTask<Void , Void, String>{
#Override
protected void onPreExecute() {
// pd.setTitle("Please Wait");
pd.setMessage("Working...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String sResponse) {
pd.dismiss();
pd.cancel();
}
}
}
I tried to recreate it, it appears to be working fine. this below method has comments explaining your actions.
private void myWOrk() {
try {
final ProgressDialog Dialog = new ProgressDialog(this);
Dialog.setMessage("Loading route...");
Dialog.show();
Thread.sleep(2000);// load url and redirect
//Toast.makeText(LoginActivity.this, "redirect caught", Toast.LENGTH_SHORT).show();
new AsyncTask<Object, Object, Object>() {
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);// authenticate
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object result) {
Toast.makeText(LoginActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Dialog.dismiss();// start your new activity here
};
}.execute(null, null, null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`

Categories

Resources