Menu Handler for the activities - java

Please help me out regarding the menu handler . I want to make menu handler which i can call in different activities . All things are working fine . list is fetching from the server and menu are also appearing but when i click on the any menu button "Force to close" Pops up .
Here is the meun handler class
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class MenuHandler extends Activity{
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
over here i want the same menu to work .
package com.droidnova.android.howto.optionmenu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Test extends ListActivity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
menuHandler = new MenuHandler(this);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}
Here is what i am getting in the logcat

Without any specific logcat feedback about the exception your code is throwing, my best guess is Android doesn't like you crossing multiple Context instances in the way that you are by instantiating one Activity inside of another.
A much better way to accomplish your goal is to use the MenuHandler as the base class for any Activity that you want to display the menu. In other words:
Leave MenuHandler alone, except for getting rid of that constructor.
Make all your Activity classes extend MenuHandler to bring in that functionality.

Related

Struggling with Shared Preferences and Lists

I'm busy with a very basic Note Taking Android App and having trouble with shared preferences.
In MainActivity is(should be) a list of the notes that were previously taken. To make a note you press menu and select make a note, that will take you to the second activity(writeANote.java).From there you make your note press menu and select add note, the it should be in in the listView(noteList). But its not... i think my problem is in MainActivity where I try to get the ArrayList from shared preferences.
I also have the ObjectSerializer class.
Please help.
Here is my code for the MainActivity.
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static SharedPreferences sp;
static ListView noteList;
//static ArrayList<String> noteArray;
//static ArrayAdapter<String> adapter;
static ArrayAdapter<String> spListAdapter;
ArrayList<String> newSpList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.makeNewNote):
Intent i=new Intent(getApplicationContext(),writeANote.class);
startActivity(i);
Log.i("SELECTED","make New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteList=(ListView)findViewById(R.id.noteList);
//noteArray= new ArrayList<String>();
//adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,noteArray);
try {
newSpList=(ArrayList<String>)ObjectSerializer.deserialize((sp.getString("spList",ObjectSerializer.serialize(new ArrayList<String>()))));
Log.i("new SP List", newSpList.get(0));
}catch(Exception e){
e.printStackTrace();
}
spListAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,newSpList);
sp= (SharedPreferences) getSharedPreferences("com.example.makeanote", Context.MODE_PRIVATE);
//String test=sp.getString("test","nothing");
newSpList.add("test");
//noteArray.add(test);
if (newSpList.size()!=0) {
noteList.setAdapter(spListAdapter);
}else{
Toast.makeText(this, "No Notes So Far", Toast.LENGTH_SHORT).show();
}
}
}
Here is my code for the second activity(writeANote.java).
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import java.util.ArrayList;
import static com.example.makeanote.MainActivity.sp;
public class writeANote extends AppCompatActivity {
EditText note;
ArrayList<String> spList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu_2,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.addNote):
//sp.edit().putString("test",).apply();
spList.add(note.getText().toString());
try {
MainActivity.sp.edit().putString("spList",ObjectSerializer.serialize(spList)).apply();
}catch(Exception e){
e.printStackTrace();
}
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
Log.i("SELECTED","add New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_a_note);
spList=new ArrayList<>();
note=findViewById(R.id.note);
}
}

Sort Array in Recyclerview (Java, Android)

package com.example.sander.app;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
ArrayList<String> cPoints = new ArrayList<>();
ArrayList<String> code = new ArrayList<>();
ArrayList<String> latitude = new ArrayList<>();
ArrayList<String> longitude = new ArrayList<>();
GPSTracker gps;
ArrayList<Double> dLatitude = new ArrayList<>();
ArrayList<Double> dLongitude = new ArrayList<>();
ArrayList<Float> distance = new ArrayList<>();
ArrayList<Data> dataList = new ArrayList<>();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_view, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Integer id = item.getItemId();
if(id == R.id.action_A_Z){
//Sorts the garages from A to Z
Collections.sort(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if(id == R.id.action_Z_A){
//Sorts the garages from Z to A
Collections.reverse(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if (id == R.id.short_distance){
Collections.sort(distance);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recycle, container, false);
final RecyclerView VRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage_all.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
if(names.size() == 0) {
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
dataList.add(new Data(jsonObject.getString("parkgarage_name"), jsonObject.getString("charging_capcatity"), jsonObject.getDouble("langitude"),
jsonObject.getDouble("longitude"), jsonObject.getString("parkgarage_code"), distance.get(i)));
//names.add(jsonObject.getString("parkgarage_name"));
//cPoints.add(jsonObject.getString("charging_capacity"));
//code.add(jsonObject.getString("parkgarage_code"));
//latitude.add(jsonObject.getString("langitude"));
//longitude.add(jsonObject.getString("longitude"));
dLatitude.add(jsonObject.getDouble("langitude"));
dLongitude.add(jsonObject.getDouble("longitude"));
}
}
} catch (JSONException ex){}
gps = new GPSTracker(getActivity());
//check if gps is on
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}
Location myLocation = new Location("");
myLocation.setLatitude(gps.getLatitude());
myLocation.setLongitude(gps.getLongitude());
for(int z = 0; z < latitude.size(); z++){
Location parkingGarage = new Location("");
parkingGarage.setLatitude(dLatitude.get(z));
parkingGarage.setLongitude(dLongitude.get(z));
distance.add(myLocation.distanceTo(parkingGarage)/1000);
}
VRecyclerView.setHasFixedSize(true);
//RecycleAdapter adapter = new RecycleAdapter(names, cPoints, code, latitude, longitude, distance);
RecycleAdapter adapter = new RecycleAdapter(dataList);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
return view;
}
}
This is my RecycleFrame code, below is my RecyclerAdapter code
package com.example.sander.app;
import android.app.Fragment;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
ArrayList<Data> ArrayListData;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView TextViewNames;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
TextViewNames = (TextView) v.findViewById(R.id.text_view_names);
}
}
public RecycleAdapter(ArrayList<Data> names){
ArrayListData = names;
//ArrayCharging= cPoints;
//ArrayCode = code;
//ArrayLatitude = latitude;
//ArrayLongitude = longitude;
//ArrayDistance = distance;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.TextViewNames.setText(String.valueOf(ArrayListData.get(position)));
//holder.TextViewNames.setText("Naam: " + ArrayNames.get(position));
//holder.TextViewCharging.setText("Oplaadpunten: " + ArrayCharging.get(position));
//holder.TextViewCode.setText("Code: " + ArrayCode.get(position));
//holder.TextViewLatitude.setText("Positie: (" + ArrayLatitude.get(position) + ", " + ArrayLongitude.get(position)+ ")");
//holder.TextViewDistance.setText(String.valueOf(ArrayDistance.get(position)));
//holder.mImageView.setImageResource(R.drawable.ic_local_parking_black_24dp);
}
#Override
public int getItemCount() { return ArrayListData.size(); }
}
What I want is the following: I want to be able to press a item in a 3 dot menu and sort it from A to Z, Z to A & sort in on distance to the certain location. Sorting works correct (except for the distance but I can fix that myself). The only problem is that when I sort from A to Z or Z to A or distance the code & name & cPoints are not matching anymore. Does anyone know how to fix this?
As per you code you have multiple arraylist for name, distance, cpoint and when you sort one list the mapping between sorted list and all others list lost.
To fix this you have to keep the mapping between all whenever you sort based on attribute.
Better create a custom class with fields like name, distance, cpoint.... and whenever you sort on one attribute sort the list of custom objects. By this way mapping between multiple list is not lost.
There is another inefficient approach to solve the problem. But I will not recommend.
Try to sort the 4 array simultaneously based on one key. Like if you want to sort based on name, try to implement the selection sort on name array and on swapping swap elements in all four array to maintain the mapping between all four. Performance of sorting is not good in this solution. To implement this refer How to sort multiple ArrayLists based off order of another?

store multiple views in recylerview using sharedpreferences on runtime

Hi am using a "Add" button in ActionBar of my app on clicking it a ListView gets open and the user can tap on any list item to add that item to the RecyclerView which is the parent activity(MainActivity holding the Recyclerview) but on exiting the app the last added item stays on MainActivity's view. I guess SharedPreferences' Editor is getting overwritten everytime. Can you please help in providing some snippet as i can't call editor.put() method multiple times as the click happens on listView. My RecyclerView contains an image and a text.
Here is my MainActivity's Code
package com.example.mohitmehndiratta.customlistadap;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.support.v7.widget.LinearLayoutManager.*;
public class MainActivity extends AppCompatActivity {
public static ArrayList<DataSet> alist;
int i;
RecyclerView rv;
static RecycledAdap adap;
static String args;
static int rid;
static SharedPreferences sharedPreferences;
public static void addnow(String arg)
{
args=arg;
rid=R.drawable.i;
alist.add(new DataSet(args,rid));
adap.notifyDataSetChanged();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("Iconid",rid);
editor.putString("AppName",args);
editor.apply();
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.new_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.addbtn)
{
Intent intent=new Intent(this,AppList.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("MyPrefs",getApplicationContext().MODE_PRIVATE);
rv=(RecyclerView)findViewById(R.id.rv);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.addItemDecoration(new ItemDecoration(this, LinearLayoutManager.VERTICAL));
for(i=0;i<DataModel.name.length;i++) {
alist = new ArrayList<DataSet>();
alist.add(new DataSet("Paytm",R.drawable.i));
alist.add(new DataSet("Facebook",R.drawable.i1));
alist.add(new DataSet("ShareIt",R.drawable.i2));
alist.add(new DataSet("Instagram",R.drawable.i3));
alist.add(new DataSet("BookMyShow",R.drawable.i4));
}
adap=new RecycledAdap(getApplicationContext(),alist);
rv.setAdapter(adap);
MyListener mlistener=new MyListener(getApplicationContext(),rv, new MyListener.ReClickListener() {
#Override
public void onClick(int position) {
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
#Override
public void onLongClick(int position) {
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
});
rv.addOnItemTouchListener(mlistener);
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
else
{
Toast.makeText(getApplication(),"There is nothing in app's cache",Toast.LENGTH_SHORT).show();
}
}
}
ListView code :
package com.example.mohitmehndiratta.customlistadap;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AppList extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
PackageManager pm=getPackageManager();
ArrayList<ApplicationInfo> li= (ArrayList<ApplicationInfo>) pm.getInstalledApplications(0);
ArrayList al=new ArrayList<String>();
String str;
String strpk;
ApplicationInfo info;
for(int i=0;i<li.size();i++)
{
info=li.get(i);
str=info.loadLabel(pm).toString();
Drawable appicon=info.loadIcon(pm);
al.add(str);
}
lv=(ListView)findViewById(R.id.listView);
final ArrayAdapter adap=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,al);
lv.setAdapter(adap);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String text=lv.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),text+i,Toast.LENGTH_SHORT).show();
MainActivity.addnow(text);
}
});
}
}

How to display a listview with only matched items while typing than all (unmatched)items at once?

The list loads with all the strings , and when matched , shows the matched items . But , I want that list shows only when search is typed in , and the list has only the items searched for .
package com.example.searchlistview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
private static final String TAG = "SearchViewFilterMode";
private SearchView mSearchView;
String data,temp,users;
private ListView mListView;
private ArrayAdapter<String> mAdapter;
private final ArrayList<String> mstrings_arr=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
try
{
ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://192.162.1.126:1234/www/search_reg_users.php");
HttpResponse res=client.execute(post);
InputStream inp=res.getEntity().getContent();
BufferedReader bf=new BufferedReader(new InputStreamReader(inp));
//since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code
data="";
temp="";
while((temp=bf.readLine())!=null)
{
data=data+temp;
}
JSONArray array=new JSONArray(data);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
users=object.getString("username");
mstrings_arr.add(users);
Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
mListView.setAdapter(mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
mstrings_arr));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.cheese_hunt_hint));
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
}
After the above code , I tried , setting the visibility of the listview to be VISIBILE only when a match is found . It is working for only one search instance , and if a match is found , entire list is returned .
What is I wish to get , are as follows :
Enter a search in search box
If that search matches any item in the list item
ONLY THEN , the list is displayed but with ONLY MATCHED ITEM
else {
mListView.setFilterText(newText.toString());
mListView.setVisibility(View.VISIBLE);
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
You need to use addTextChangedListener to solve your issue here. I've worked on similar thing.
addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
}
}
});
AutoCompleteTextView served the purpose , finally
package com.example.searchlistview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.Layout;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
//public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
public class MainActivity extends Activity{
private static final String TAG = "SearchViewFilterMode";
private SearchView mSearchView;
String data,temp,users;
private ListView mListView;
private final ArrayList<String> mstrings_arr=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
ArrayAdapter<String> mAdapter=new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,mstrings_arr);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
try
{
ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://192.168.1.16:1234/www/search_reg_users.php");
HttpResponse res=client.execute(post);
InputStream inp=res.getEntity().getContent();
BufferedReader bf=new BufferedReader(new InputStreamReader(inp));
//since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code
data="";
temp="";
while((temp=bf.readLine())!=null)
{
data=data+temp;
}
JSONArray array=new JSONArray(data);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
users=object.getString("username");
mstrings_arr.add(users);
Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
//AutoCompleteSearchView
AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(mAdapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
XML , for the same is :
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="36dp"
android:layout_marginTop="17dp"
android:ems="10"
android:text="">
<requestFocus />
</AutoCompleteTextView>

Cannot query current user's friend list and add to listview android with parse

I've tried to to query of current user's friend list and add it to listview in android. The problem is the method keep showing errors
This is my code
package com.example.krisanapongpoonsawat.chatit;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import com.parse.FindCallback;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
public class User extends AppCompatActivity {
private ArrayList<ParseUser> uList;
/** The user. */
public static ParseUser user;
ArrayList<String> friendlist;
ArrayAdapter<String> listAdapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
final ParseUser currentUser = ParseUser.getCurrentUser();
list = (ListView) findViewById(R.id.listView);
listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
list.setAdapter(listAdapter);
}
#Override
protected void onResume()
{
super.onResume();
loadUserList();
}
private void loadUserList()
{
ParseQuery query = new ParseQuery("Friends");
query.whereEqualTo("owner", ParseUser.getCurrentUser().getObjectId().toString());
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> friendList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + friendList.size() + " scores");
for (int i = 0; i < friendlist.size(); i++) {
Object object = friendlist.get(i);
String name = ((ParseObject) object).getObjectId().toString();
listAdapter.add(name);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
// User chose the "Settings" item, show the app settings UI...
Intent intent = new Intent(User.this, Search.class);
startActivity(intent);
finish();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
and the error shown is
Error:(66, 51) error: <anonymous com.example.krisanapongpoonsawat.chatit.User$1> is not abstract and does not override abstract method done(List,ParseException) in FindCallback
Error:(67, 25) error: name clash: done(List<ParseObject>,ParseException) in <anonymous com.example.krisanapongpoonsawat.chatit.User$1> and done(List<T>,ParseException) in FindCallback have the same erasure, yet neither overrides the other
where T is a type-variable:
T extends ParseObject declared in interface FindCallback
Can you solve this? I've been stuck with it for 3 days now
let me know if you need any additional info!
Thank you
Here you have a lot of informations about relations
Reffering to this documentation and our conversation in comments, I think your query should look like that:
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.whereEqualTo("owner", ParseUser.getCurrentUser().getObjectId().toString());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> friendList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + friendList.size() + " scores");
for (int i = 0; i < friendList.size(); i++) {
ParseObject item = friendList.get(i);
ParseRelation<ParseObject> friendRelation = item.getRelation("Friends");
ParseQuery friendsQuery = friendRelation.getQuery();
findFriends(friendsQuery);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
...
private void findFriends(ParseQuery query) {
query.findInBackground(new FindCallback() {
...
});
}
It is very likely that something in my answer may not work, but I have no other idea.

Categories

Resources