I have to compare two .txt files. Below is my code..
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/file1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="File 1" />
<Button
android:id="#+id/file2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/file1"
android:layout_below="#+id/file1"
android:text="File 2" />
<Button
android:id="#+id/compare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/file2"
android:layout_below="#+id/file2"
android:layout_marginTop="16dp"
android:text="Compare" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
FileOutputStream fos;
FileInputStream fOne, fTwo;
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fileOne = (Button)findViewById(R.id.file1);
Button fileTwo = (Button)findViewById(R.id.file2);
Button compare = (Button)findViewById(R.id.compare);
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr2.add("2");
arr2.add("3");
fileOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File1", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr1.size(); temp++)
{
fos.write((arr1.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
fileTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File2", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr2.size(); temp++)
{
fos.write((arr2.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
compare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fOne = openFileInput("File1");
fTwo = openFileInput("File2");
Scanner scanFileOne = new Scanner(new DataInputStream(fOne));
Scanner scanFileTwo = new Scanner(new DataInputStream(fTwo));
while (scanFileOne.hasNextLine())
{
String first = scanFileOne.next();
String second = scanFileTwo.next();
if(first.equals(second))
{
count++;
}
}
Toast.makeText(getBaseContext(), "" + count, 1000).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}
What I have to do is on Compare button click, I have to compare content of both files and message should be prompted. But here my app force closes..What needs to be done?
your while loop needs to check that both files have a next line that can be retrieved
while (scanFileOne.hasNextLine() && scanFileTwo.hasNextLine())
Related
I am a newbie in android development.In my music player app, whenever I click the play/pause button to pause the song , nothing happens. It seems like the imagebutton is not clickable because nothing happens on touching it. I am not able to pause the song playing. I have tried all possible solutions mentioned on stack overflow still its not working.Can anyone tell me what am I doing wrong ?
XML File :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="1">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright">
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_weight="2.40"
android:background="#null"
android:paddingLeft="10dp"
android:src="#drawable/btn_previous" />
<ImageButton
android:id="#+id/btnPlay1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:clickable="true"
android:background="#drawable/btn_play" />
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:paddingLeft="230dp"
android:src="#drawable/btn_next" />
</RelativeLayout>
</LinearLayout>
btn_play.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/download4"
android:state_enabled="false" />
<item android:drawable="#drawable/az"
android:state_enabled="true" />
</selector>
PlayListActivity.java :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc(){
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setOnClickListener(
new ImageButton.OnClickListener(){
public void onClick(View v){
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
Your Adapter doesnt seen to be in the same LayoutXML, maybe your findViewById(R.id.btnPlay1) are returning null.
Your listener change it to this :
btnPlay1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Act.this, "test click", Toast.LENGTH_SHORT).show();
}
});
I'm new to Android and was working on my first app. I was trying to parse the contents of a Google Sheets spreadsheets, specifically a list of names into a Spinner. I've done so successfully by using an ArrayAdapter with an ArrayList as I can see the options when I expand the Spinner. The problem I'm facing is that the Spinner doesn't show the currently selected item when one is selected. If you try to run my code, you'll see that if you try to click the submit Button, it'll tell you that null is being selected, so I've narrowed down my problem to the currently selected name String not being selected.
Here is my MainActivity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ArrayList<String> names = new ArrayList<String>();
Spinner spBusinessType;
Button btnsubmit;
ArrayAdapter<String> adapterBusinessType;
String sbusinesstype;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spBusinessType = (Spinner) findViewById(R.id.spBussinessType);
btnsubmit=(Button)findViewById(R.id.submit);
btnsubmit.setOnClickListener(this);
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=1JKU2Vt_gMNUYYALct4m9xElLdpGlQ3N4uhS9qFRzxOQ");
adapterBusinessType = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
adapterBusinessType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBusinessType.setAdapter(adapterBusinessType);
spBusinessType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
sbusinesstype = adapter.getItemAtPosition(position).toString();
System.out.println(sbusinesstype);
// Showing selected spinner item
Toast.makeText(getApplicationContext(),
"Bussiness Type : " + sbusinesstype, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You have selected " + sbusinesstype,Toast.LENGTH_SHORT).show();
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
String name = columns.getJSONObject(0).getString("v");
names.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the AsyncResult interface I'm using to obtain a JSON object from Google Sheets:
public interface AsyncResult
{
void onResult(JSONObject object);
}
the DownloadWebpageTask class that is obtaining and parsing the JSON object:
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
AsyncResult callback;
public DownloadWebpageTask(AsyncResult callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to download the requested page.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// remove the unnecessary parts from the response and construct a JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
try {
JSONObject table = new JSONObject(jsonResponse);
callback.onResult(table);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String downloadUrl(String urlString) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = convertStreamToString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
the activity_main layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<include layout="#layout/content_main" />
</RelativeLayout>
and the content_main layout file that I put the Spinner in:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity">
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Business Type"
android:textColor="#000000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spBussinessType"
style="#style/Base.Widget.AppCompat.Spinner.Underlined"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Spinner>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Submit"
android:textSize="15sp" />
</LinearLayout>
What is causing the adapter to not detect when one of the name strings is being selected? Could it be related to how I'm parsing them from the Google Sheet?
You didnt notify the ArrayAdapter that the data has changed, you originally passed empty Arraylist and upon filling the array list, you have to notifiy the Adapter that data has changed and its time for it to consider that, something like
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
String name = columns.getJSONObject(0).getString("v");
names.add(name);
}
adapterBusinessType.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
That should help.
It would appear no data is being displayed in your Adapter. Nothing can be selected. Your listener code looks fine.
Put adapterBusinessType.notifyDatasetChanged() into the processJson method. Outside the catch or after you add all the data to the list.
Or... replace names.add with adapterBusinessType.add
How i can create paging for my WebView that fill from Epub.
My MainActivity.java :
public class MainActivity extends ActionBarActivity implements OnClickListener {
WebView webView;
Handler hand;
String data = null;
LinearLayout books;
int pagecount = 1;
Book book;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hand = new Handler();
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
AssetManager assetManager = getAssets();
try {
InputStream epubInputStream = assetManager.open("mybook.epub");
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("Log_one", "author(s): " + book.getMetadata().getAuthors());
Log.i("Log_two", "title: " + book.getTitle());
Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
Log.i("Log_three", "Coverimage is " + coverImage.getWidth() + " by " + coverImage.getHeight() + " pixels");
logTableOfContents(book.getTableOfContents().getTocReferences(), 0);
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences();
int count = spineList.size();
Button btnnext = (Button) findViewById(R.id.btnNext);
Button btnPreviuse = (Button) findViewById(R.id.btnPreviuse);
btnnext.setOnClickListener(this);
btnPreviuse.setOnClickListener(this);
} catch (IOException e) {
Log.e("Log_four", e.getMessage());
}
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("Log_five", tocString.toString());
logTableOfContents(tocReference.getChildren(), depth + 1);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNext) {
try {
int i = pagecount + 7;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(i).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
} else if (v.getId() == R.id.btnPreviuse) {
try {
int i = pagecount - 1;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(i).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When i click on Button I need to see another page but i can't see .
My activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/book"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="#+id/Footer"
android:layout_width="match_parent"
android:layout_height="100dip"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="#+id/btnNext"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:text="Next Page" />
<Button
android:id="#+id/btnPreviuse"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:text="Previuse Page" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
How i can create paging on my page .
#Override
public void onClick(View v) {
if(v.getId() == R.id.btnNext){
try {
books.removeAllViews();
int i = pagecount + y;
y = i;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(y).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}else if(v.getId() == R.id.btnPreviuse){
try {
books.removeAllViews();
int i = y - pagecount;
y = i;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(y).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am trying to use Chris Banes' library Actionbar-PullToRefresh. It can be found here.
I am using Tabs at bottom of screen in my app. as you can see in screen shot.
I read through the sample code. He says that all you have to do is, wrap your refreshable view in a PullToRefreshLayout like this: How do i integrate it into my app.
public class MainActivity extends Activity implements OnTabChangeListener {
private TabHost mTabHost;
public static final String TAB_1 = "Open";
public static final String TAB_2 = "Approved";
public static final String TAB_3 = "Decline";
private int mCurrentTab;
public String result;
Vector<String> msgvector = new Vector<String>();
Vector<String> usernamevector = new Vector<String>();
Vector<String> feedIdvector = new Vector<String>();
Vector<String> userIdvector = new Vector<String>();
ListView listview,listview1,listview2;
private ProgressDialog simpleWaitDialog;
List<Rowfeeds> rowfeedlist;
public String result2;
public String result3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
listview = (ListView)findViewById(R.id.tab_1);
listview1 = (ListView)findViewById(R.id.tab_2);
listview2 = (ListView)findViewById(R.id.tab_3);
new Feedsdata().execute();
setupTabs();
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
}
private class Feedsdata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
Log.i("doInBackground", "doInBackground");
HttpClient hc = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://192.168.21.74/mynetwork/formapi/top_feeds");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("from", "0"));
nameValuePairs.add(new BasicNameValuePair("to", "10"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse rp = hc.execute(postMethod);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(rp.getEntity());
Log.v("suggestion_data", "" + result);
JSONArray jsonary = new JSONArray(result);
for (int i = 0; i < jsonary.length(); i++) {
//Log.v("jsonary.length", "" +jsonary.length());
String sr = ""+jsonary.getJSONObject(i);
//Log.v("sr", "" +sr);
JSONObject jobj = new JSONObject(sr);
Log.v("======================", "=================" );
Log.v("feed_id", "" +jobj.getString("feed_id"));
Log.v("feed_message", "" +jobj.getString("feed_message"));
Log.v("user_id", "" +jobj.getString("user_id"));
Log.v("username", "" +jobj.getString("username"));
Log.v("======================", "=================" );
msgvector.add(""+jobj.getString("feed_message").toString().trim());
usernamevector.add("" +jobj.getString("username").toString().trim());
feedIdvector.add("" +jobj.getString("feed_id").toString().trim());
userIdvector.add("" +jobj.getString("user_id").toString().trim());
}
//for (int i = 0; i < feedIdvector.size(); i++) {
//Log.v("feedIdvector", "" +feedIdvector.elementAt(i));
//}
}else{
Log.d("JSON", "StatusCode "+rp.getStatusLine().getStatusCode());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("AsyncTaskException", e.toString());
}
Log.i("popularAsyncTaskException", e.toString());
}
return null;
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(MainActivity.this,"Wait", "Downloading feeds");
}
#Override
protected void onPostExecute(String result) {
rowfeedlist = new ArrayList<Rowfeeds>();
for (int i = 0; i < msgvector.size(); i++) {
Rowfeeds rowfeeds = new Rowfeeds(msgvector.elementAt(i),usernamevector.elementAt(i),feedIdvector.elementAt(i));
rowfeedlist.add(rowfeeds);
}
Customfeedadapter feedadapter = new Customfeedadapter(getApplicationContext(),R.layout.feeds,rowfeedlist
,feedIdvector,userIdvector);
listview.setAdapter(feedadapter);
simpleWaitDialog.dismiss();
}
private void setupTabs() {
mTabHost.setup(); // you must call this before adding your tabs!
mTabHost.addTab(newTab(TAB_1, R.id.tab_1));
mTabHost.addTab(newTab(TAB_2, R.id.tab_2));
mTabHost.addTab(newTab(TAB_3, R.id.tab_3));
}
private TabSpec newTab(String tag, int tabContentId) {
Log.i("tag", tag);//fff498
Log.i("tabContentId", ""+tabContentId);//fff498
TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(tabContentId);
if(tag.equalsIgnoreCase("Open")){
spec.setIndicator("", getResources().getDrawable(R.drawable.feed));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Approved")){
spec.setIndicator("", getResources().getDrawable(R.drawable.trend));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Decline")){
spec.setIndicator("", getResources().getDrawable(R.drawable.popularr));
spec.setContent(tabContentId);
}
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#fff498"));
}
return spec;
}
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Xml layout:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0" >
</TabWidget>
</LinearLayout>
</TabHost>
Put all your list views in PullToRefreshLayout and give R.id.tab_1 R.id.tab_2 R.id.tab_3 id's to your PullToRefreshLayout instead of ListView
<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab_1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
same for rest of the listview
In java inside onCreate of the activity:
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mPullToRefreshLayout= (ListView)findViewById(R.id.tab_1);
mPullToRefreshLayout1 = (ListView)findViewById(R.id.tab_2);
mPullToRefreshLayout2 = (ListView)findViewById(R.id.tab_3);
listview = (ListView)findViewById(R.id.listview1);
listview1 = (ListView)findViewById(R.id.listview2);
listview2 = (ListView)findViewById(R.id.listview3);
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
on tab change:
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout1);
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout2);
}
}
I want to implement search directly from the data on server. For example search from google.com. A edittext, like in search bar of google a word in edittext then it hits the server and fetch the records starting from that word.
public class SearchActivity extends Activity {
TextView imeino;
Spinner select;
EditText searchby;
StringBuffer URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
imeino = (TextView)findViewById(R.id.getimeino);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
imeino.setText(device_id);
searchby = (AutoCompleteTextView)findViewById(R.id.editText1);
//this is a spinner if i choose mobile from this then edittext only takes numeric value.and if a select name then it takes alphabets.
select = (Spinner)findViewById(R.id.spinner1);
select.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(select.getSelectedItem().toString().equals("Mobile"))
{
searchby.setInputType(InputType. TYPE_CLASS_PHONE|InputType.TYPE_TEXT_VARIATION_PHONETIC);
}
if(select.getSelectedItem().toString().equals("name"))
{
searchby.setInputType(InputType. TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
}
if(select.getSelectedItem().toString().equals("Address"))
{
searchby.setInputType(InputType. TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
this is my edittext in which i have to search for data
searchby.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchby = (AutoCompleteTextView)findViewById(R.id.editText1);
String getitemforsearch = searchby.getText().toString();
SearchFromCustomerData(getitemforsearch);
}
public void SearchFromCustomerData(String getitemforsearch) {
String searchType= new String();
if(select.getSelectedItem().toString().equals("Mobile"))
{
searchType= "CustomerMobile";
}
if(select.getSelectedItem().toString().equals("Address"))
{
searchType= "CustomerAddress";
}
if(select.getSelectedItem().toString().equals("name"))
{
searchType= "CustomerName";
}
This is my url to hit web service and it will show options
URL = new StringBuffer("?"+searchType+"=" + getitemforsearch+"&searchType="+searchType);
try {
URL sever = new URL(URL.toString());
System.out.println(URL.toString());
URLConnection yc = sever.openConnection();
InputStream in = yc.getInputStream(); // Get the data in the entity
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null) {
sb.append(read);
read = br.readLine();
}
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray resultArray = jsonObject.getJSONArray("Customer");
System.out.println(" Length :" + resultArray.length());
String[] CustomerCode = new String[resultArray.length()];
String[] CustomerName = new String[resultArray.length()];
String[] CustomerEmail = new String[resultArray.length()];
String[] CustomerMobile = new String[resultArray.length()];
String[] Customeraddress = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
JSONObject object = (JSONObject) resultArray.get(i);
System.out.println("true");
CustomerCode[i] = object.getString("CustomerCode") == null ? "" : object.getString("CustomerCode");
CustomerName[i] = object.getString("CustomerName") == null ? "" : object.getString("CustomerName");
CustomerEmail[i] = object.getString("CustomerEmailId") == null ? "" : object.getString("CustomerEmailId");
CustomerMobile[i] = object.getString("CustomerMobile") == null ? "" : object.getString("CustomerMobile");
Customeraddress[i] = object.getString("CustomerAddress") == null ? "" : object.getString("CustomerAddress");
}
}
catch (Exception e) {
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
here is my layout file..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SearchActivity" >
<TextView
android:id="#+id/getimeino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="ImEiNo..." />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/getimeino"
android:layout_marginTop="30dp"
android:entries="#array/process_arrays"
android:prompt="#string/process_prompt" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/getimeino"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>