Make CheckBox in ListView visible/invisible - android

Hey guys i am building an app that has a listview in its MainActivity. I have a checkbox on every list item but in the beggining i want it to be invisible and then when the user clicks a button in the actionbar the visibility of the checkbox to be visible. i have done this but the visibility appears only in the first item. how is it possible to make it happen to all items?
My code is
List<HashMap<String, String>> stocksList;
ArrayList<String> imageUrl;
Bitmap bmp;
public CheckBox dontShowAgain;
public Configuration newConfig;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean network_connected = activeNetwork != null
&& activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();
if (!network_connected) {
onDetectNetworkState().show();
} else {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
accessWebService();
registerCallClickBack();
}
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equals("checked")){
onAlertMobileData().show();
}
if(skipMessage.equals("checked")){
accessWebService();
registerCallClickBack();
}
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.Share:{
accessWebService();
registerCallClickBack();
return true;
}
case R.id.About:{
onAboutPressed().show();
return true;
}
case R.id.item1:{
CheckBox chk = (CheckBox)findViewById(R.id.checkBoxMainList);
chk.setVisibility(CheckBox.VISIBLE);
}
default:{
return false;
}
}
}
And this is where the list is being created:
public void ListDrawer() {
stocksList = new ArrayList<HashMap<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String price1 = jsonChildNode.optString("price1");
String price2 = jsonChildNode.optString("price2");
String price3 = jsonChildNode.optString("price3");
String price4 = jsonChildNode.optString("price4");
String price5 = jsonChildNode.optString("price5");
String price6 = jsonChildNode.optString("price6");
String price7 = jsonChildNode.optString("price7");
String price8 = jsonChildNode.optString("price8");
String price9 = jsonChildNode.optString("price9");
String price10 = jsonChildNode.optString("price10");
String price11 = jsonChildNode.optString("price11");
String price12 = jsonChildNode.optString("price12");
String price13 = jsonChildNode.optString("price13");
String price14 = jsonChildNode.optString("price14");
String price15 = jsonChildNode.optString("price15");
stocksList.add(createStockList(name, price, price1, price2, price3, price4, price5, price6, price7, price8, price9, price10, price11, price12, price13, price14, price15));
}
} catch (Exception e) {
//Toast.makeText(getApplicationContext(), "Error" + e.toString(),
//Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, RefreshActivity.class);
startActivityForResult(intent1, 0);
}
String[] from = { "name", "price"};
int[] to = { R.id.stock_name, R.id.stock_price};
SimpleAdapter simpleAdapter = new SimpleAdapter(this, stocksList,
R.layout.list_item,
from, to);
listView.setAdapter(simpleAdapter);
}
public HashMap<String, String> createStockList(String name, String price, String price1, String price2, String price3, String price4, String price5, String price6, String price7, String price8, String price9, String price10, String price11, String price12, String price13, String price14, String price15) {
HashMap<String, String> stockNameNo = new HashMap<String, String>();
stockNameNo.put("name", name);
stockNameNo.put("price", price);
stockNameNo.put("price1", price1);
stockNameNo.put("price2", price2);
stockNameNo.put("price3", price3);
stockNameNo.put("price4", price4);
stockNameNo.put("price5", price5);
stockNameNo.put("price6", price6);
stockNameNo.put("price7", price7);
stockNameNo.put("price8", price8);
stockNameNo.put("price9", price9);
stockNameNo.put("price10", price10);
stockNameNo.put("price11", price11);
stockNameNo.put("price12", price12);
stockNameNo.put("price13", price13);
stockNameNo.put("price14", price14);
stockNameNo.put("price15", price15);
return stockNameNo;
}
Any help will be much appreciated and accepted. Thanks in advance!

You will have to do it in your adapter instead of the activity class. In the getView method of your SimpleAdapter, trap the click event and set a boolean variable to true. In the getView method, if the boolean variable is set, show the checkboxes. If it is unset, hide the checkbox.

Related

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Array index in searchview get mixed up

SearchActivity as below:
public class SearchActivity 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 SimpleCursorAdapter myAdapter;
SearchView searchView = null;
private WarehouseSalesDetails[] strArrData;
private String selectedID;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search_item);
Toolbar toolBarSearch = (Toolbar)findViewById(R.id.toolbarSearch);
setSupportActionBar(toolBarSearch);
final String[] from = new String[]{"title"};
final int[] to = new int[]{android.R.id.text1};
//setup SimpleCursorAdapter
myAdapter = new SimpleCursorAdapter(SearchActivity.this,android.R.layout.simple_spinner_dropdown_item,null,from,to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
new RetrieveWarehouseSalesTask(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_search,menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager)SearchActivity.this.getSystemService(Context.SEARCH_SERVICE);
if(searchItem!=null){
searchView = (SearchView) searchItem.getActionView();
}
if(searchView!=null){
searchView.setSearchableInfo(searchManager.getSearchableInfo(SearchActivity.this.getComponentName()));
searchView.setIconified(false);
searchView.setSuggestionsAdapter(myAdapter);
//getting selected on item suggestion
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
#Override
public boolean onSuggestionClick(int position){
//Add clicked text to search box
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(cursor.getColumnIndex("title")),false);
Log.d("strArr id",strArrData[position].id);
selectedID = strArrData[position].id;
return true;
}
#Override
public boolean onSuggestionSelect(int position){
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String s){
Intent intent = new Intent(SearchActivity.this,RetrieveIndividualWarehouseSales.class);
intent.putExtra("pid",selectedID);
startActivity(intent);
return false;
}
#Override
public boolean onQueryTextChange(String s){
//filter data
final MatrixCursor mc = new MatrixCursor(new String[]{
BaseColumns._ID,"title"
});
for(int i = 0; i<strArrData.length; i++){
if(strArrData[i].title.toLowerCase().startsWith(s.toLowerCase())){
mc.addRow(new Object[]{i,strArrData[i].title});
}
}
myAdapter.changeCursor(mc);
return false;
}
});
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
String query = intent.getStringExtra(SearchManager.QUERY);
if(searchView!=null){
searchView.clearFocus();
}
}
}
class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void> {
private String TAG = ActiveWarehouseSalesFragment.RetrieveWarehouseSalesTask.class.getSimpleName();
private String TAG_PID = "pid";
public ProgressDialog pDialog;
private Context context;
//URL to get JSON details
private String url = "http://example.com/example.php";
ArrayList<HashMap<String,String>> sales_details;
List<WarehouseSalesDetails> data = new ArrayList<>();
JSONObject jsonObj;
String jsonStr;
JSONArray sales;
//for recycler view
private RecyclerView warehouse_recycler;
private AdapterRecycler mAdapter;
public RetrieveWarehouseSalesTask(Context context){
this.context = context;
sales_details = new ArrayList<>();
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Searching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0){
HttpHandler sh = new HttpHandler();
//making a request to URL and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url (SearchActivity): " + jsonStr);
return null;
}
#Override
protected void onPostExecute(Void result){
//ArrayList<String> dataList = new ArrayList<String>();
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
if(jsonStr != null){
try{
jsonObj = new JSONObject(jsonStr);
//Getting JSON Array Node
sales = jsonObj.getJSONArray("Result");
//looping through all results
for(int i = sales.length() - 1; i >= 0 ;i--){
JSONObject s = sales.getJSONObject(i);
WarehouseSalesDetails wsd = new WarehouseSalesDetails();
wsd.id = s.getString("id");
wsd.company_name = s.getString("company_name");
wsd.promotion_image= s.getString("promotion_image");
wsd.title = s.getString("title");
wsd.promotional_period = s.getString("promotional_period");
wsd.viewCount = s.getString("view_count");
data.add(wsd);
}
//strArrData = dataList.toArray(new String[dataList.size()]);
strArrData = data.toArray(new WarehouseSalesDetails[data.size()]);
Log.d("TAG",sales_details.toString());
}catch(final JSONException e){
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}else{
Log.e(TAG,"Couldn't get json from server");
}
/*//update RecyclerView
warehouse_recycler = (RecyclerView)((AppCompatActivity) context).findViewById(R.id.recyclerView);
mAdapter = new AdapterRecycler(context, data);
System.out.println("mAdapter size is: " + mAdapter.getItemCount());
System.out.println("Data size is: " + data.size());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
warehouse_recycler.setLayoutManager(layoutManager);
//mAdapter.notifyDataSetChanged();
warehouse_recycler.setAdapter(mAdapter);
warehouse_recycler.invalidate();
*/
}
}
}
I am trying to call an activity when user make a search on the search bar. I am storing id and title in strArrData. The suggestions displayed shows correct values. However, when I clicks on either of the suggestions, it always pass in the wrong id. And I found out that, the array always stores the values of the first few json values. How should I fix this ?
Found a solution by using Hashmap.
First of all store all your json values in hashmap as below:
HashMap<String, String> idMap = new HashMap<String, String>();
idMap.put(s.getString("id"),s.getString("title"));
Secondly, implement this method in your class to get the hashmap key based on hashmap value:
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
And finally:
String selectedID = getKeyFromValue(idMap,selectedTitle).toString();
Log.d("selected id",selectedID);
Intent intent = new Intent(SearchActivity.this,NextActivity.class);
intent.putExtra("pid",selectedID);
startActivity(intent);

saved arrayList<HashMap<String,String>,displaying them without Internet

I have arrayList> in my app.I have this array fro, the Internet,through parsing json data. I want to save this array,then my app can be work without Internet.What can I do? I know how to stored data im SQLite,but response of query is cursor,I know that I can create custom adapter that working with cursor.But maybe I can find easier way for this?
MainActivity:
public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
Intent intent;
private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
private static final String TITLE = "title";
private static final String DESCRIPTION = "description";
private static final String IMAGE = "image";
ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
lv=(ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title1 = jsonlist.get(position).get("title");
String description1 = jsonlist.get(position).get("description");
String url1 = jsonlist.get(position).get("image");
intent = new Intent(MainActivity.this, DetailInfo.class);
intent.putExtra("title", title1);
intent.putExtra("description", description1);
intent.putExtra("url", url1);
startActivity(intent);
dbHelper = new SqlHelper(MainActivity.this);
try {
dbHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.reload) {
new ProgressTask(MainActivity.this).execute();
}
else if(id == R.id.menu_item_share){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Put whatever you want");
startActivity(Intent.createChooser(intent,"Share via"));
}
return super.onOptionsItemSelected(item);
}
private class ProgressTask extends AsyncTask<String,Void,Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute(){
this.dialog.setMessage("Progress start");
this.dialog.show();
}
protected void onPostExecute(final Boolean success){
try{
if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
}
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,jsonlist, R.layout.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
lv.setAdapter(adapter);
//setListAdapter(adapter);
}catch (final IllegalArgumentException e){e.printStackTrace();}
}
protected Boolean doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for(int i =0;i<json.length();i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtitle = c.getString(TITLE);
String vdescription = c.getString(DESCRIPTION);
String vimage = c.getString(IMAGE);
/* dbHelper.createEntry(vtitle,vdescription,vimage);
dbHelper.close();*/
HashMap<String, String> map = new HashMap<>();
map.put(TITLE, vtitle);
map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
/*private void displaysavedlv(){
Cursor cursor = dbHelper.fetchAllCountries();
CustomCursorAdapter adapter1 = new CustomCursorAdapter(MainActivity.this,cursor);
lv.setAdapter(adapter1);
}*/
/* private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}*/
}
yes you can do this without sqlite. TinyDB will do the trick for you.
checkout here : https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
You can create one method in sqlite that returns arrayList with hashmap :
public ArrayList<HashMap<String, String>> getAllData()
{
ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tablename", null );
res.moveToFirst();
while(res.isAfterLast() == false){
hashmap = new HashMap<String, String>();
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Cheers!

Search hashmap for string and remove

So I'm showing images in a gridview from a json response.
Each image comes in a json response like:
{poster_path=/u1LHo5ObRZA1r8pzSq0OqQ2qlaU.jpg, vote_average=0.0, title=The Beauty Inside, vote_count=0, overview=Woo-Jin changes into a different person when he wakes up. He falls in love with Yi-Soo., id=338729, release_date=2015-08-20}
poster_path contains the image url.
When the poster_path is null like:
{poster_path=null, vote_average=0.0, title=The Bad Education Movie, vote_count=0, overview=Mr Wickers and his class go on one final school trip after they finish their GCSEs., id=348296, release_date=2015-08-21}
I want to remove this item in my Hashmap if it contains poster_path=null so it doesn't load that data into my gridView.
How can this be done?
Here is my activity which downloads and parses the json response:
public class Upcoming extends android.support.v4.app.Fragment {
private static final String KEY_POSITION = "position";
private static final String TAGG = "TMDB Pop Movies";
private static final String apiKey = "MYKEY";
private static final String tmdbURL = "MYURL";
private static final String TAG_MOVIES = "results";
static final String TAG_ID = "id";
static final String TAG_RELEASE = "release_date";
static final String TAG_TITLE = "title";
static final String TAG_POSTER = "poster_path";
static final String TAG_VOTE_AVG = "vote_average";
static final String TAG_VOTE_COUNT = "vote_count";
static final String TAG_OVERVIEW = "overview";
String NumberOfPage = "&page=1";
ArrayList<HashMap<String, String>> mylist;
JSONObject json = null;
JSONArray results = null;
UpcomingGridViewAdapter adapter;
GridView Gridv;
int numberofpagesshown = 0;
private String position;
private OnFragmentInteractionListener mListener;
public static Upcoming newInstance(int position) {
Upcoming fragment = new Upcoming();
Bundle args = new Bundle();
args.putInt(KEY_POSITION, position);
fragment.setArguments(args);
return fragment;
}
public Upcoming() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getString(KEY_POSITION);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View newview = inflater.inflate(R.layout.fragment_upcoming, container, false);
//Initialize with empty data
mylist = new ArrayList<HashMap<String, String>>();
// Start download void
new DownloadJSON().execute();
return newview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
// Downloading data asynchronously
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... url) {
json = JSONfunctions.getJSONfromURL(tmdbURL + "/3/movie/upcoming"
+ apiKey + NumberOfPage);
try {
// Get the array of movies
results = json.getJSONArray(TAG_MOVIES);
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String poster = r.getString(TAG_POSTER);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
Gridv = (GridView) getActivity().findViewById(R.id.upcoming_gridlayout);
adapter = new UpcomingGridViewAdapter(getActivity(), mylist);
Gridv.setAdapter(adapter);
}
else {
adapter.notifyDataSetChanged();
}
// Attach the listener to the AdapterView onCreate
Gridv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if (numberofpagesshown == 1) {
NumberOfPage = "&page=2";
new DownloadJSON().execute();
} else if (numberofpagesshown == 2) {
NumberOfPage = "&page=3";
new DownloadJSON().execute();
} else if (numberofpagesshown == 3) {
NumberOfPage = "&page=4";
new DownloadJSON().execute();
} else if (numberofpagesshown == 4) {
NumberOfPage = "&page=5";
new DownloadJSON().execute();
} else if (numberofpagesshown == 5) {
NumberOfPage = "&page=6";
new DownloadJSON().execute();
}
}
});
}
}
}
And finally the gridView Adapter:
public class UpcomingGridViewAdapter extends BaseAdapter {
public boolean pressedMovieItem;
Context context;
ArrayList<HashMap<String, String>> data;
// Will store json data
HashMap<String, String>mylist = new HashMap<>();
public UpcomingGridViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.upcoming_grid_item, parent, false);
}
final ImageView poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
mylist = data.get(position);
final String posterPath = mylist.get("poster_path");
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
final String url = "http://image.tmdb.org/t/p/w185" + posterPath;
if(mylist.get("poster_path") != "null") {
// load image url into poster
Picasso.with(context).load(url).into(poster);
}
else{
// load image url into poster
// Picasso.with(context).load(R.drawable.ic_local_movies_black_24dp).into(poster);
poster.setBackgroundColor(Color.parseColor("#F5F5F5"));
// poster.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
}
Just change you for loop inside doInBackground() like this. It would simply won't add that node in ArrayList
for (int i = 0; i < results.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals(""))
continue;
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
Made a little modification:
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals("")|| poster.equals("null"))
continue;
else {
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}

Swipe listview item detailed activity left or right to slide view in android

I have a listview, when i click on any item in listview a detailed activity will open.This layout has many widgets like textview, ImageView, share buttons etc. Now I want to slide this detail activity of the item to show the detail view of next item in the list. I am following this http://misha.beshkin.lv/android-swipe-gesture-implementation/ but when i swipe from left to right next view is not displaying just getting a toast message "swipe right". Can any one direct me how to work on this? i am new to android Answers will be appreciated. Following is the code i have used
MainActivity.java(listview page)
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://siteurl/posts/pages";
static final String KEY_URL_FOR_MAP = "url_site";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_SITEURL = "url";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String siteurl = c.getString(KEY_SITEURL);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_URL_FOR_MAP, siteurl);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
final ListView list=(ListView)findViewById(android.R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
startActivity(in);
}
});
}
}
SampleDesp.java(detailed Activity)
public class SampleDesp extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
static String title;
String content;
// Your Facebook APP ID
private static String APP_ID = "308180782571605"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
Button btnPostToWall;
// JSON node keys
static final String KEY_URL_FOR_MAP = "url_site";
private static final String KEY_TITLE = "title";
private static final String KEY_SITEURL = "url";
private static final String KEY_DATE = "date";
private static final String KEY_NAME = "name";
private static final String KEY_CONTENT = "content";
private static final String KEY_URL = "url";
static final String KEY_SLUG1= "slug";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sampledes);
detector = new SimpleGestureFilter(this,this);
final LinearLayout line1 = (LinearLayout)findViewById(R.id.ll1);
LinearLayout line2 = (LinearLayout)findViewById(R.id.ll2);
Button btnShare = (Button)findViewById(R.id.share);
btnShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
line1.setVisibility(View.VISIBLE);
}
});
// getting intent data
Intent in = getIntent();
final String url1 = in.getStringExtra(KEY_URL);
ImageView imgv = (ImageView) findViewById(R.id.imgdesc);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
imageLoader.DisplayImage(url1, imgv);
// Get JSON values from previous intent
final String title = in.getStringExtra(KEY_TITLE);
final String siteurl = in.getStringExtra(KEY_URL_FOR_MAP);
String date = in.getStringExtra(KEY_DATE);
String name = in.getStringExtra(KEY_NAME);
final String content = in.getStringExtra(KEY_CONTENT);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblUrl = (TextView) findViewById(R.id.url_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
TextView lblCont = (TextView) findViewById(R.id.content_label);
lblName.setText(title);
lblUrl.setText(siteurl);
lblCost.setText(date);
lblDesc.setText(name);
lblCont.setText(content);
final ImageView email3 = (ImageView) findViewById(R.id.email);
email3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//my codes
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + title + "&body=" + content);
intent.setData(data);
startActivity(intent);
}
});
final ImageView sms4 = (ImageView) findViewById(R.id.sms);
sms4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setData(Uri.parse(Uri.encode(title)+Uri.encode(content)));
shareIntent.setType("text/*");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, content);
startActivity(shareIntent);
}
});
final ImageView twitter4 = (ImageView) findViewById(R.id.twitter);
twitter4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(title) + "" + Uri.encode(siteurl)));
startActivity(i);
}
});
Button btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
if (facebook.isSessionValid()) {
postToWall();
}
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
/**
* Function to login into facebook
* */
private void loginToFacebook() {
// TODO Auto-generated method stub
{
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}else{}
}
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("title", "visit us");
parameters.putString("link", "http://india.dollardesi.net/ads/metro-logistic-packers-movers/");
// post on user's wall.
facebook.dialog(this, "feed",parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
SimpleGestureFilter.java
public class SimpleGestureFilter extends SimpleOnGestureListener{
public final static int SWIPE_UP = 1;
public final static int SWIPE_DOWN = 2;
public final static int SWIPE_LEFT = 3;
public final static int SWIPE_RIGHT = 4;
public final static int MODE_TRANSPARENT = 0;
public final static int MODE_SOLID = 1;
public final static int MODE_DYNAMIC = 2;
private final static int ACTION_FAKE = -13; //just an unlikely number
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
private int mode = MODE_DYNAMIC;
private boolean running = true;
private boolean tapIndicator = false;
private Activity context;
private GestureDetector detector;
private SimpleGestureListener listener;
public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {
this.context = context;
this.detector = new GestureDetector(context, this);
this.listener = sgl;
}
public void onTouchEvent(MotionEvent event){
if(!this.running)
return;
boolean result = this.detector.onTouchEvent(event);
if(this.mode == MODE_SOLID)
event.setAction(MotionEvent.ACTION_CANCEL);
else if (this.mode == MODE_DYNAMIC) {
if(event.getAction() == ACTION_FAKE)
event.setAction(MotionEvent.ACTION_UP);
else if (result)
event.setAction(MotionEvent.ACTION_CANCEL);
else if(this.tapIndicator){
event.setAction(MotionEvent.ACTION_DOWN);
this.tapIndicator = false;
}
}
//else just do nothing, it's Transparent
}
public void setMode(int m){
this.mode = m;
}
public int getMode(){
return this.mode;
}
public void setEnabled(boolean status){
this.running = status;
}
public void setSwipeMaxDistance(int distance){
this.swipe_Max_Distance = distance;
}
public void setSwipeMinDistance(int distance){
this.swipe_Min_Distance = distance;
}
public void setSwipeMinVelocity(int distance){
this.swipe_Min_Velocity = distance;
}
public int getSwipeMaxDistance(){
return this.swipe_Max_Distance;
}
public int getSwipeMinDistance(){
return this.swipe_Min_Distance;
}
public int getSwipeMinVelocity(){
return this.swipe_Min_Velocity;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final float xDistance = Math.abs(e1.getX() - e2.getX());
final float yDistance = Math.abs(e1.getY() - e2.getY());
if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
return false;
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
boolean result = false;
if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
if(e1.getX() > e2.getX()) // right to left
this.listener.onSwipe(SWIPE_LEFT);
else
this.listener.onSwipe(SWIPE_RIGHT);
result = true;
}
else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
if(e1.getY() > e2.getY()) // bottom to up
this.listener.onSwipe(SWIPE_UP);
else
this.listener.onSwipe(SWIPE_DOWN);
result = true;
}
return result;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
this.tapIndicator = true;
return false;
}
#Override
public boolean onDoubleTap(MotionEvent arg0) {
this.listener.onDoubleTap();;
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent arg0) {
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent arg0) {
if(this.mode == MODE_DYNAMIC){ // we owe an ACTION_UP, so we fake an
arg0.setAction(ACTION_FAKE); //action which will be converted to an ACTION_UP later.
this.context.dispatchTouchEvent(arg0);
}
return false;
}
static interface SimpleGestureListener{
void onSwipe(int direction);
void onDoubleTap();
}
}
I think that it may work:
//code from your onItemClick
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing incremented position
startActivity(in);
And then in your details Activity you will have position of current item of the list that details are displayed on the screen. So now you can increment position, and use the same code (the above one) in your onSwipe(int direction) method. So if you want to open next item details on your left swipe you do something like this:
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT :
break;
case SimpleGestureFilter.SWIPE_LEFT :
Intent in = getIntent();
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing clicked position
finish();
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN :
break;
case SimpleGestureFilter.SWIPE_UP :
break;
}
}
But for this code in SWIPE_LEFT when your adding Extras to your intent, you need access to a HashMap from your MainActivity, so you can add a public static method in your MainActivity like:
public static String getSongFromHashMap(String key) {
return songsList.get(key);
}
And use this method in SWIPE_LEFT code. I know it's not best solution but it should work :)
change
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
to
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
//Fire intent to your detail activity here
break;
I hope I am closer to your solution.

Categories

Resources