Connecting WAMP server with Android 1.3 - java

I created my WAMPserver and started a project in the wwww directory file. However, when it comes to Android studio, I am not being able to import the corresponding classes to makes the server run via my app.
import android.os.AsyncTask;
import android.os.Bundle;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
The error is "Cannot resolve symbol".
NOTE: The error can be solved if i change the buildToolsVersion in my build.grade file to "22.2.0". But it is not working in this case.
my buildToolVersion is "23.0.1"
This is the complete code: Mainly I am detecting devices with WiFi-Direct enabled.. but now i wish to insert the data in the database on the server (That i can't seem able to integrate)
package com.example.georges.mobilenetworking.Wifi_P2P;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.AsyncTask;
import android.os.Bundle;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.example.georges.mobilenetworking.R;
import java.util.ArrayList;
import java.util.List;
public class Wifi_P2P extends AppCompatActivity {
private final String serverURL = "127.0.0.1/451database";
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
public List<String> l = new ArrayList<String>();
public List peers = new ArrayList();
public ArrayAdapter<String> arrayAdapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi__p2_p);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new Wifi_P2P_Receiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
// scan for devices
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d("DRCT", "discovering peers success !!");
displayPeers();
}
#Override
public void onFailure(int reasonCode) {
}
});
}
#Override
public void onResume() {
super.onResume();
mReceiver = new Wifi_P2P_Receiver(mManager, mChannel, this);
registerReceiver(mReceiver, mIntentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
#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_wifi__p2, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
void displayPeers(){
lv = (ListView) findViewById(R.id.p2p);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, l);
lv.setAdapter(arrayAdapter);
}
}
Any suggestions ?

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);
}
}

I am making an android app that involves creating a text file. How do i specify the path where I want it to appear?

I am new to android development, I think that something is wrong with the Uri built = Uri.parse("/storage/sdcard0/Download/");, but I don't know what. Any help would be appreciated.
package com.example.ecobinary;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final int CREATE_FILE = 1;
private void createFile(Uri pickerInitialUri) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, "testing.txt");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, CREATE_FILE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button execute_button = findViewById(R.id.execute_button);
execute_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri built = Uri.parse("/storage/sdcard0/Download/");
createFile(built);
}
});
}
}

How can I open a file content placed in a listView?

So, I manage to list all the files that I saved from and edit text into a listview and it works fine. What I want now is to open them into an edit text field. There is my code down below. How can I do that ? I hope you'll help me.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TextView;
import android.app.ListActivity;
public class Tab1 extends Activity
{
private ToggleButton toggleButton1;
private ImageView imageViewOn;
private TextView textReceive;
private Button refresh;
EditText txtData;
int data_block =100;
private long lastTime = 0;
private List<String> myList;
private File file;
final Handler handler = new Handler() {
public void handleMessage(Message msg)
{
String data = msg.getData().getString("receivedData");
// Affichage de data
long t = System.currentTimeMillis();
if(t-lastTime > 100)
{
textReceive.append("\n");
lastTime = System.currentTimeMillis();
}
textReceive.append(data);
}
};
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg)
{
int co = msg.arg1;
if(co == 1) {
} else if(co == 2) {
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab1);
ListView listView = (ListView) findViewById(R.id.listView1);
myList = new ArrayList<String>();
File directory = Environment.getExternalStorageDirectory();
file = new File(directory + "/Notes");
final File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
Study View.setTag(string) method in android documentation. Then in your adapter class use view.setTag(param) ... Replace the view by the view name which you are returning and Param by file path ...
Next, in onItemClick method call view.getTag(). This will return the file path. Open the file then using its path. I hope you got the point.

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>

Categories

Resources