public class MainActivity extends AppCompatActivity implements
Response.Listener<JSONObject>,
Response.ErrorListener,
AdapterView.OnItemClickListener {
EditText movienameText;
Button getButton;
TextView yearText,genreText,titleText,plotText,nameText;
ListView moviesList;
private ResourceBundle response;
ArrayAdapter<String> adapter;
ArrayList<String>moviesname=new ArrayList<String>();
ArrayList<String>moviesyear=new ArrayList<String>();
ArrayList<String>moviesgenre=new ArrayList<String>();
ArrayList<String>moviesplot=new ArrayList<String>();
String x,plot,genre,year;
RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movienameText=findViewById(R.id.MovienameText);
getButton=findViewById(R.id.getButton);
moviesList=findViewById(R.id.moviesList);
moviesList.setOnItemClickListener(this);
adapter=newArrayAdapter<String(this,android.R.layout.
simple_list_item_1, moviesname);
}
public void get(View view) {
queue = Volley.newRequestQueue(this);
String url1="http://www.omdbapi.com
/?s="+movienameText.getText().toString()+"&apikey=1a382b30";
JsonObjectRequest request1=new
JsonObjectRequest(Request.Method.GET,url1,null,this,this);
queue.add(request1);
}
#Override
public void onResponse(JSONObject response) {
try {
for (int i = 0; i <response.getJSONArray("Search").length(); i++) {
if (i<response.getJSONArray("Search").length()){
moviesname.add(response.getJSONArray("Search").getJSONObject(i)
.getString("Title"));
}
else{
break;
}
}
moviesList.setAdapter(adapter);
year=response.getString("Year");
} catch (JSONException e) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} }
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show(); }
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
year=response.getString("Year");
x = moviesList.getItemAtPosition(position).toString();
String url2="http://www.omdbapi.com
/?t="+moviesList.getItemAtPosition(position).toString().replace("
","")+"&apikey=1a382b30";
JsonObjectRequest request2=new
JsonObjectRequest(Request.Method.GET,url2,null,this,this);
queue.add(request2);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage(x).create().show();
builder.setMessage(year).create().show(); // builder.setMessage(genre).create().show(); // builder.setMessage(plot).create().show();
}
}
when I type a movie name with two words like(die hard) it Enters on error method, but I don't know why?..................................................................................................................................................................................................................................
Probably you have to encode your movienameText.getText(). Http links don't allow spaces.
Try to do:
String url1 = TextUtils.htmlEncode("http://www.omdbapi.com/?s="+movienameText.getText().toString()+"&apikey=1a382b30");
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");
I have an asynTask to get all the events from server. This data from asyncTask I want to show as a list in a dialog. How can I do this?
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.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
// Toast.makeText(PlanEventActivity.this,
// "OnCancelListener",
// Toast.LENGTH_LONG).show();
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// "OnDismissListener",
// Toast.LENGTH_LONG).show();
}});
//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) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// parent.getItemAtPosition(position).toString() + " clicked",
// Toast.LENGTH_LONG).show();
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog the list I am showing as a string. How can I show list of data from asyncTask? Thank you..
I wrote code for connecting with Facebook and extracting username,email ID and Profile link .All the extracted details displays in different activity on the click of a button.But I wanted it to display it in the same actiivty as soon the login process is completed successfully.which means I need to edit the code after onSuccess but I don't no how to get the code
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
Button share,details;
ShareDialog shareDialog;
LoginButton login;
ProfilePictureView profile;
Dialog details_dialog;
TextView details_txt;
TextView details_txtx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
login = (LoginButton)findViewById(R.id.login_button);
profile = (ProfilePictureView)findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
share = (Button)findViewById(R.id.share);
details = (Button)findViewById(R.id.details);
login.setReadPermissions("public_profile email");
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txtx = (TextView)details_txtx.findViewById(R.id.details_tetx);
details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
details_dialog.show();
}
});
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(AccessToken.getCurrentAccessToken() != null) {
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
profile.setProfileId(null);
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShareLinkContent content = new ShareLinkContent.Builder().build();
shareDialog.show(content);
}
});
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult ) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
public void RequestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String text = "<b>Name :</b> "+json.getString("name")+"<br><br><b>Email :</b> "+json.getString("email")+"<br><br><b>Profile link :</b> "+json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
To be Clear: All i wanted is to display the extracted details in the same activity after a successful login can you please help with it.?
please check the following code
protected void connectToFacebook() {
ArrayList<String> list = new ArrayList<String>();
list.add("email");
// LoginManager.getInstance().logInWithReadPermissions(this, list);
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
// Application code
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String fbUserId = json.optString("id");
String fbUserFirstName = json.optString("name");
String fbUserEmail = json.optString("email");
String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
callApiForCheckSocialLogin(fbUserId, fbUserFirstName, fbUserEmail, fbUserProfilePics, "fb");
}
Log.v("FaceBook Response :", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
// Log.v("LoginActivity", "" + exception);
Utilities.showToast(mActivity, "" + exception);
}
});
}
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