Data in Adapter but not loding in Listview | converted Listactivity to ListFragment - android-listview

I have converted Many Activities to Fragment, all are working fine except one. In the Previous version of this java file, it was extending ListActivity, now I have replaced it with ListFragment. Initially it was giving a nullPointerException, but with help of this post, I managed to remove error. Now it is fetching data in Adapter but not in listview (which I checked by printing it in log). So I need to show data in listview.
Here is Java code:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.net.URLConnection;
import android.support.v4.app.Fragment;
public class listtojson extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
// public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listFileDir.php";
public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php";
//public static String url = "http://www.newsvoice.in/sites/listNewsSites.php";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
private static final String TAG_PHONE_URL = "url";
private static final String TAG_FILETYPE = "filetype";
private static final String TAG_FILETYPETXT = "filetypetxt";
private static final String TAG_DETAILS = "details";
private static final String TAG_FILEPATH = "filepath";
private static final String TAG_LOCATION = "location";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_USERNAME = "username";
private static final String TAG_HIGHALERT= "highalert";
// public ImageLoader imageLoader;
public int ssid ;
// contacts JSONArray
JSONArray contacts = null;
public TextView view1;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
View fragment;
LinearLayout llLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
llLayout = (LinearLayout) inflater.inflate(R.layout.listnewsjson, container, false);
contactList = new ArrayList<HashMap<String, String>>();
fragment = inflater.inflate(R.layout.listnewsjson, container, false);
return llLayout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = (ListView) fragment.findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String size = ((TextView) view.findViewById(R.id.size))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String details = ((TextView) view.findViewById(R.id.details))
.getText().toString();
String location = ((TextView) view.findViewById(R.id.location))
.getText().toString();
String datetime = ((TextView) view.findViewById(R.id.datetime))
.getText().toString();
String filetype = ((TextView) view.findViewById(R.id.filetypetxt))
.getText().toString();
String username = ((TextView) view.findViewById(R.id.username))
.getText().toString();
//String highalert = ((TextView) view.findViewById(R.id.highalert)).getText().toString();
//ImageView thumb_image=(ImageView)view.findViewById(R.id.filetype);
// ImageView image = (ImageView) view.findViewById(R.id.filetype);
// thumb image
//= String filetype = ((ImageView) view.findViewById(R.id.filetype))
//= .getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
fileDownloader.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_SIZE, cost);
in.putExtra(TAG_PHONE_URL, description);
startActivity(in);
*/
Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class);
// passing sqlite row id
//= in.putExtra(TAG_ID, sqlite_id);
in.putExtra(TAG_ID, String.valueOf(id));
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DETAILS, details);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_DATETIME, datetime);
in.putExtra(TAG_FILETYPE, filetype);
in.putExtra(TAG_PHONE_URL, description);
in.putExtra(TAG_SIZE, size);
in.putExtra(TAG_USERNAME, username);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
//return llLayout;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading People News");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
try {
// Making a request to url and getting response
// String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
URL requestUrl = new URL(url);
Log.e("Debug", " Sapp 1 : " + requestUrl.toString());
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
//Reader rd=new Readable(in);
int cp;
try {
while((cp=in.read())!=-1){
sb.append((char)cp);
}}
catch(Exception e){
}
String jsonStr=sb.toString();
Log.e("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String url = c.getString(TAG_PHONE_URL);
String details = c.getString(TAG_DETAILS);
String location = c.getString(TAG_LOCATION);
String datetime = c.getString(TAG_DATETIME);
String filetype = c.getString(TAG_FILETYPE);
String username = c.getString(TAG_USERNAME);
String highalert = c.getString(TAG_HIGHALERT);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_SIZE, size);
contact.put(TAG_PHONE_URL, url);
contact.put(TAG_DETAILS, details);
contact.put(TAG_LOCATION, location);
contact.put(TAG_DATETIME, datetime);
contact.put(TAG_FILETYPE, filetype);
contact.put(TAG_FILETYPETXT, filetype);
contact.put(TAG_USERNAME, username);
contact.put(TAG_HIGHALERT, highalert);
// Log.e("Debug", " Sapp 7 : " + name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}catch(Exception ec){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE,
TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name,
R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert });
Log.e("Debug", " Sapp 10" + TAG_NAME+contactList.toString());
//Here it is printing the array in Log
//Problem seems here
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11"+view.getId());
if (view.getId() == R.id.name) {
((TextView) view).setText((String) data);
return true;
} else if (view.getId() == R.id.size) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.url) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.details) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.location) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.datetime) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.filetypetxt) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.username) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10,20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert=(String.valueOf((String) data));
if(halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
return true;
}
else { return true; }
} else if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res =getResources();
String tnew=(String.valueOf((String) data));
String tst=tnew;
int sidd=0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if(tst.equals("c")) { ssid = R.drawable.ca; }
else if(tst.equals("d")) { ssid = R.drawable.da; }
else if(tst.equals("e")) { ssid = R.drawable.ea; }
//s=2130837566;
Log.e("Debug", " Sapp 8 :"+ssid+":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
};
((SimpleAdapter) adapter).setViewBinder(viewBinder);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
}
public static String getFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
and Here is xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</LinearLayout>

Some suggestions:
No need for View fragment; and its initialization: fragment = inflater.inflate(R.layout.listnewsjson, container, false); Remove them.
Replace lv = (ListView) fragment.findViewById(android.R.id.list); with lv = getListView();. getListView() is a method defined by ListFragment that returns the fragment's ListView.
IMPORTANT: Replace lv.setAdapter(adapter); in onPostExecute() with setListAdapter(adapter);. From documentation of ListFragment:
You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.
Modify setViewValue() method of viewBinder to:
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11" + view.getId());
if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10, 20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert = (String.valueOf((String) data));
if (halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
} else {
// TODO: Should remove gradient color here because views are recycled.
}
return true;
}
if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res = getResources();
String tnew = (String.valueOf((String) data));
String tst = tnew;
int sidd = 0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if (tst.equals("c")) {
ssid = R.drawable.ca;
} else if (tst.equals("d")) {
ssid = R.drawable.da;
} else if (tst.equals("e")) {
ssid = R.drawable.ea;
}
//s=2130837566;
Log.e("Debug", " Sapp 8 :" + ssid + ":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
ViewBinder only needs to handle cases where you need to do something extra (like setting background color or loading images based on passed-in data values in your case) than just simply binding values to views. Ordinary binding of values to views is provided by SimpleAdapter by default.

Related

Flutter video player is not buffering

Video player is not buffering and the controller always false of isBuffering property
_controller.value.isBuffering
when i seek to a place i passed it re-download the video again .
I've tried to use other plugins but all of them depend on video_player under the hood
how to solve this issue ?
Replace this code with the code inside VideoPlayer.java file which is located inside video_player package. Then it will work
Link to file in github
package io.flutter.plugins.videoplayer;
import static com.google.android.exoplayer2.Player.REPEAT_MODE_ALL;
import static com.google.android.exoplayer2.Player.REPEAT_MODE_OFF;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Player.EventListener;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import io.flutter.plugin.common.EventChannel;
import io.flutter.view.TextureRegistry;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
final class VideoPlayer {
private static final String FORMAT_SS = "ss";
private static final String FORMAT_DASH = "dash";
private static final String FORMAT_HLS = "hls";
private static final String FORMAT_OTHER = "other";
private SimpleExoPlayer exoPlayer;
private Surface surface;
private final TextureRegistry.SurfaceTextureEntry textureEntry;
private QueuingEventSink eventSink = new QueuingEventSink();
private final EventChannel eventChannel;
private boolean isInitialized = false;
VideoPlayer(
Context context,
EventChannel eventChannel,
TextureRegistry.SurfaceTextureEntry textureEntry,
String dataSource,
String formatHint) {
this.eventChannel = eventChannel;
this.textureEntry = textureEntry;
TrackSelector trackSelector = new DefaultTrackSelector();
exoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
Uri uri = Uri.parse(dataSource);
DataSource.Factory dataSourceFactory;
if (isHTTP(uri)) {
dataSourceFactory =
new DefaultHttpDataSourceFactory(
"ExoPlayer",
null,
DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
true);
} else {
dataSourceFactory = new DefaultDataSourceFactory(context, "ExoPlayer");
}
MediaSource mediaSource = buildMediaSource(uri, dataSourceFactory, formatHint, context);
exoPlayer.prepare(mediaSource);
setupVideoPlayer(eventChannel, textureEntry);
}
private static boolean isHTTP(Uri uri) {
if (uri == null || uri.getScheme() == null) {
return false;
}
String scheme = uri.getScheme();
return scheme.equals("http") || scheme.equals("https");
}
private MediaSource buildMediaSource(
Uri uri, DataSource.Factory mediaDataSourceFactory, String formatHint, Context context) {
int type;
if (formatHint == null) {
type = Util.inferContentType(uri.getLastPathSegment());
} else {
switch (formatHint) {
case FORMAT_SS:
type = C.TYPE_SS;
break;
case FORMAT_DASH:
type = C.TYPE_DASH;
break;
case FORMAT_HLS:
type = C.TYPE_HLS;
break;
case FORMAT_OTHER:
type = C.TYPE_OTHER;
break;
default:
type = -1;
break;
}
}
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
new DefaultDataSourceFactory(context, null, mediaDataSourceFactory))
.createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
new DefaultDataSourceFactory(context, null, mediaDataSourceFactory))
.createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(mediaDataSourceFactory)
.setExtractorsFactory(new DefaultExtractorsFactory())
.createMediaSource(uri);
default:
{
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private void setupVideoPlayer(
EventChannel eventChannel, TextureRegistry.SurfaceTextureEntry textureEntry) {
eventChannel.setStreamHandler(
new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink sink) {
eventSink.setDelegate(sink);
}
#Override
public void onCancel(Object o) {
eventSink.setDelegate(null);
}
});
surface = new Surface(textureEntry.surfaceTexture());
exoPlayer.setVideoSurface(surface);
setAudioAttributes(exoPlayer);
exoPlayer.addListener(
new EventListener() {
#Override
public void onPlayerStateChanged(final boolean playWhenReady, final int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
sendBufferingUpdate();
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingStart");
eventSink.success(event);
} else if (playbackState == Player.STATE_READY) {
if (isInitialized) {
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingEnd");
eventSink.success(event);
} else {
isInitialized = true;
sendInitialized();
}
} else if (playbackState == Player.STATE_ENDED) {
Map<String, Object> event = new HashMap<>();
event.put("event", "completed");
eventSink.success(event);
}
}
#Override
public void onPlayerError(final ExoPlaybackException error) {
if (eventSink != null) {
eventSink.error("VideoError", "Video player had error " + error, null);
}
}
});
}
void sendBufferingUpdate() {
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingUpdate");
List<? extends Number> range = Arrays.asList(0, exoPlayer.getBufferedPosition());
// iOS supports a list of buffered ranges, so here is a list with a single range.
event.put("values", Collections.singletonList(range));
eventSink.success(event);
}
#SuppressWarnings("deprecation")
private static void setAudioAttributes(SimpleExoPlayer exoPlayer) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
exoPlayer.setAudioAttributes(
new AudioAttributes.Builder().setContentType(C.CONTENT_TYPE_MOVIE).build());
} else {
exoPlayer.setAudioStreamType(C.STREAM_TYPE_MUSIC);
}
}
void play() {
exoPlayer.setPlayWhenReady(true);
}
void pause() {
exoPlayer.setPlayWhenReady(false);
}
void setLooping(boolean value) {
exoPlayer.setRepeatMode(value ? REPEAT_MODE_ALL : REPEAT_MODE_OFF);
}
void setVolume(double value) {
float bracketedValue = (float) Math.max(0.0, Math.min(1.0, value));
exoPlayer.setVolume(bracketedValue);
}
void seekTo(int location) {
exoPlayer.seekTo(location);
}
long getPosition() {
return exoPlayer.getCurrentPosition();
}
#SuppressWarnings("SuspiciousNameCombination")
private void sendInitialized() {
if (isInitialized) {
Map<String, Object> event = new HashMap<>();
event.put("event", "initialized");
event.put("duration", exoPlayer.getDuration());
if (exoPlayer.getVideoFormat() != null) {
Format videoFormat = exoPlayer.getVideoFormat();
int width = videoFormat.width;
int height = videoFormat.height;
int rotationDegrees = videoFormat.rotationDegrees;
// Switch the width/height if video was taken in portrait mode
if (rotationDegrees == 90 || rotationDegrees == 270) {
width = exoPlayer.getVideoFormat().height;
height = exoPlayer.getVideoFormat().width;
}
event.put("width", width);
event.put("height", height);
}
eventSink.success(event);
}
}
void dispose() {
if (isInitialized) {
exoPlayer.stop();
}
textureEntry.release();
eventChannel.setStreamHandler(null);
if (surface != null) {
surface.release();
}
if (exoPlayer != null) {
exoPlayer.release();
}
}
}

GWT CellTree inside a DataGrid does not react to mouse-clicks

I have put a GWT-CellTree in a DataGrid. It works except for one thing: When clicking on the tree-expand-icon, nothing happens. I have tried to minimize the
code needed to reproduce the problem...
How can this be fixed ?
best regards, Magnus
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
DataGrid grid= (DataGrid) new NodesGrid().getTable();
grid.setWidth("100%");
SimpleLayoutPanel slp = new SimpleLayoutPanel();
slp.add(grid);
RootLayoutPanel.get().add(slp);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class NodesGrid {
private AbstractCellTable<Node> table = new DataGrid<>();
private Column nameColumn;
private Column<Node, String> showBlocksColumn;
private final Set<Integer> showBlocks = new HashSet<>();
public Column getNameColumn() {
return nameColumn;
}
public AbstractCellTable<Node> getTable() {
return table;
}
public NodesGrid() {
table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
table.setWidth("100%");
CustomCellTableBuilder c = new CustomCellTableBuilder(this, table);
table.setTableBuilder(c);
Node nodes = new Node();
nodes.setName("hello");
nodes.setId(123);
Node n2 = new Node();
n2.setName("testing");
nodes.getBlocks().add(n2);
ListDataProvider<Node> dataProvider = new ListDataProvider<>();
dataProvider.addDataDisplay(table);
List<Node> list = dataProvider.getList();
list.add(nodes);
addShowBlocks();
nameColumn = getSorter(list, "Name", Comparator.comparing(Node::getName), Node::getName);
}
private Column getSorter(List<Node> list,
String name,
Comparator<Node> cmp,
Function<Node, String> supplier) {
TextColumn<Node> column = new TextColumn<Node>() {
#Override
public String getValue(Node object) {
return supplier.apply(object);
}
};
table.addColumn(column, name);
column.setSortable(true);
ColumnSortEvent.ListHandler<Node> columnSortHandler = new ColumnSortEvent.ListHandler<>(list);
columnSortHandler.setComparator(column, cmp);
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(column);
return column;
}
public Column<Node, String> getShowBlocksColumn() {
return showBlocksColumn;
}
public Set<Integer> getShowBlocks() {
return showBlocks;
}
void addShowBlocks() {
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>)");
return sb.toSafeHtml();
}
};
showBlocksColumn = new Column<Node, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(Node node) {
if (showBlocks.contains(node.getId())) {
return "hide blocks";
} else {
return "show blocks";
}
}
};
showBlocksColumn.setFieldUpdater(new FieldUpdater<Node, String>() {
#Override
public void update(int index, Node node, String value) {
if (showBlocks.contains(node.getId())) {
showBlocks.remove(node.getId());
} else {
showBlocks.add(node.getId());
}
table.redrawRow(index);
}
});
table.addColumn(showBlocksColumn);
table.setColumnWidth(0, 10, Style.Unit.EM);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import java.util.ArrayList;
import java.util.List;
public class NodesTree {
private CellTree tree;
public NodesTree(Node node) {
TreeViewModel model = new CustomTreeModel(node);
tree = new CellTree(model, null);
tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
TreeNode rootNode = tree.getRootTreeNode();
openAll(rootNode);
}
private static class TopLevel {
private final String name;
private List<Node> blocks = new ArrayList<>();
public TopLevel(String name) {
this.name = name;
}
public TopLevel(String name, List<Node> blocks) {
this.name = name;
this.blocks = blocks;
}
public String getName() {
return name;
}
public List<Node> getBlocks() {
return blocks;
}
}
private static class CustomTreeModel implements TreeViewModel {
private final List<TopLevel> topLevels;
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<>();
public CustomTreeModel(Node node) {
topLevels = new ArrayList<>();
{
TopLevel blocksNode = new TopLevel("Blocks", new ArrayList(node.getBlocks()));
topLevels.add(blocksNode);
}
{
TopLevel outgoing = new TopLevel("Outgoing");
topLevels.add(outgoing);
}
{
TopLevel incoming = new TopLevel("Incoming");
topLevels.add(incoming);
}
}
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
ListDataProvider<TopLevel> dataProvider
= new ListDataProvider<>(
topLevels);
Cell<TopLevel> cell = new AbstractCell<TopLevel>() {
#Override
public void render(Context context, TopLevel value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof TopLevel) {
// LEVEL 1.
ListDataProvider<Node> dataProvider = new ListDataProvider<>(((TopLevel) value).getBlocks());
Cell<Node> cell = new AbstractCell<Node>() {
#Override
public void render(Context context, Node value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped("(" + value.getName() + ")");
}
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof Node) {
// LEVEL 2 - LEAF.
String params = "test";
ArrayList<String> str = new ArrayList<>();
str.add(params);
ListDataProvider<String> dataProvider = new ListDataProvider<>(str);
return new DefaultNodeInfo<>(dataProvider, new TextCell(), selectionModel, null);
}
return null;
}
public boolean isLeaf(Object value) {
if (value instanceof String) {
return true;
}
return false;
}
}
private void openAll(TreeNode rootNode) {
if (rootNode == null) return;
for (int i = 0; i < rootNode.getChildCount(); i++) {
TreeNode node = rootNode.setChildOpen(i, true);
openAll(node);
}
}
public Widget getWidget() {
return tree;
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.AbstractCellTableBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.view.client.SelectionModel;
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Node> {
NodesGrid nodesGrid;
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
/**
* Construct a new table builder.
*
* #param cellTable the table this builder will build rows for
*/
public CustomCellTableBuilder(NodesGrid nodesGrid, AbstractCellTable<Node> cellTable) {
super(cellTable);
this.nodesGrid = nodesGrid;
AbstractCellTable.Style style = cellTable.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
#Override
protected void buildRowImpl(Node rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super Node> selectionModel = cellTable.getSelectionModel();
boolean isSelected =
(selectionModel == null || rowValue == null) ? false : selectionModel
.isSelected(rowValue);
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
buildRow(row, rowValue, cellStyles, nodesGrid.getShowBlocksColumn());
buildRow(row, rowValue, cellStyles, nodesGrid.getNameColumn());
row.endTR();
if (nodesGrid.getShowBlocks().contains(rowValue.getId())) {
buildBlockRow(rowValue, cellStyles);
}
}
void buildRow(TableRowBuilder row, Node rowValue, String cellStyles, Column column) {
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
renderCell(td, createContext(0), column, rowValue);
td.endTD();
}
private void buildBlockRow(Node rowValue, String cellStyles) {
TableRowBuilder row = startRow();
buildCell(rowValue, cellStyles, row);
row.endTR();
}
private void buildCell(Node rowValue, String cellStyles, TableRowBuilder row) {
NodesTree hw = new NodesTree(rowValue);
TableCellBuilder td = row.startTD().colSpan(5);
td.className(cellStyles);
DivBuilder div = td.startDiv();
String t = hw.getWidget().getElement().getInnerHTML();
div.html(SafeHtmlUtils.fromTrustedString(t));
div.end();
td.endTD();
}
}
package com.raybased.gwt.configtool.client.grid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Node implements Serializable {
String name;
List<Node> blocks = new ArrayList<>();
String params;
int id;
public Node() {
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Node> getBlocks() {
return blocks;
}
}

URL issue in Facebook in BlackBerry

I have integrated Facebook in my app and trying to share some content.When I call FaceBookMain() ,it shows error like :
"Success
SECURITY WARNINNG:Please treat the URL above as you would your password and do not share it with anyone."
Sometimes this error comes after login with Facebook in browser(Webview) otherwise it comes just after clicking on share button.
Most important thing here is ,I am not facing this problem in simulator.Sharing with Facebook is working properly in Simulator but not in Device.
I am adding some class files with it:
Here is FacebookMain.java class:
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.UiApplication;
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID = "406758776102494";//"533918076671162" ;
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public static boolean isFacebookScreen = false;
public FacebookMain(String postMessge) {
this.postMessage= postMessge;
isFacebookScreen = true;
checkPermissions();
fbc=new FacebookContext(NEXT_URL, APPLICATION_ID);
loginScreen = new LoginScreen(fbc,"KingdomConnect: "+postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
/*ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);*/
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {}
}
It is Facebook.java class:
public class Facebook {
protected Logger log = Logger.getLogger(getClass());
public static String API_URL = "https://graph.facebook.com";
public Facebook() {
}
public static Object read(String path, String accessToken) throws FacebookException {
return read(path, null, accessToken);
}
public static Object read(String path, Parameters params, String accessToken) throws FacebookException {
Hashtable args = new Hashtable();
args.put("access_token", accessToken);
args.put("format", "JSON");
if ((params != null) && (params.getCount() > 0)) {
Enumeration paramNamesEnum = params.getParameterNames();
while (paramNamesEnum.hasMoreElements()) {
String paramName = (String) paramNamesEnum.nextElement();
String paramValue = params.get(paramName).getValue();
args.put(paramName, paramValue);
}
}
try {
StringBuffer responseBuffer = HttpClient.getInstance().doGet(API_URL + '/' + path, args);
if (responseBuffer.length() == 0) {
throw new Exception("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Throwable t) {
t.printStackTrace();
throw new FacebookException(t.getMessage());
}
}
public static Object write(String path, Object object, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
try {
JSONObject jsonObject = (JSONObject) object;
Enumeration keysEnum = jsonObject.keys();
while (keysEnum.hasMoreElements()) {
String key = (String) keysEnum.nextElement();
Object val = jsonObject.get(key);
if (!(val instanceof JSONObject)) {
data.put(key, val.toString());
}
}
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
public static Object delete(String path, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
data.put("method", "delete");
try {
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
}
And it is BrowserScreen.class:
public class BrowserScreen extends ActionScreen {
// int[] preferredTransportTypes = { TransportInfo.TRANSPORT_TCP_CELLULAR, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_BIS_B };
int[] preferredTransportTypes = TransportInfo.getAvailableTransportTypes();//{ TransportInfo.TRANSPORT_BIS_B };
ConnectionFactory cf;
BrowserFieldConfig bfc;
BrowserField bf;
String url;
public BrowserScreen(String pUrl) {
super();
url = pUrl;
cf = new ConnectionFactory();
cf.setPreferredTransportTypes(preferredTransportTypes);
bfc = new BrowserFieldConfig();
bfc.setProperty(BrowserFieldConfig.ALLOW_CS_XHR, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.MDS_TRANSCODING_ENABLED, Boolean.FALSE);
bfc.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
bfc.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
// bfc.setProperty(BrowserFieldConfig.CONNECTION_FACTORY, cf);
bf = new BrowserField(bfc);
}
public void browse() {
show();
fetch();
}
public void show() {
add(bf);
}
public void fetch() {
bf.requestContent(url);
}
public void hide() {
delete(bf);
}
}
If any body has any clue or want some more related code to get it,please let me know.
do not use secure connection. use http instead of https.
you can refer here
same problem is presented in stackoverflow
facebook warning

Autocomplete textbox highlighting the typed character in the suggestion list

I have been working on AutoCompleteTextView. I was able to get the suggestion and all in the drop down list as we type.
My question is: Can we highlight the typed character in the suggestion drop down list?
I have achieved the functionality. The solution is as follows:
AutoCompleteAdapter.java
public class AutoCompleteAdapter extends ArrayAdapter<String> implements
Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
LayoutInflater inflater;
String text = "";
public AutoCompleteAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>(fullList);
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public String getItem(int position) {
return fullList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// tvViewResourceId = (TextView) view.findViewById(android.R.id.text1);
String item = getItem(position);
Log.d("item", "" + item);
if (convertView == null) {
convertView = view = inflater.inflate(
android.R.layout.simple_dropdown_item_1line, null);
}
// Lookup view for data population
TextView myTv = (TextView) convertView.findViewById(android.R.id.text1);
myTv.setText(highlight(text, item));
return view;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix != null) {
text = prefix.toString();
}
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>(
mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
String item = values.get(i);
if (item.toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.values != null) {
fullList = (ArrayList<String>) results.values;
} else {
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
public static CharSequence highlight(String search, String originalText) {
// ignore case and accents
// the same thing should have been done for the search text
String normalizedText = Normalizer
.normalize(originalText, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.toLowerCase(Locale.ENGLISH);
int start = normalizedText.indexOf(search.toLowerCase(Locale.ENGLISH));
if (start < 0) {
// not found, nothing to to
return originalText;
} else {
// highlight each appearance in the original text
// while searching in normalized text
Spannable highlighted = new SpannableString(originalText);
while (start >= 0) {
int spanStart = Math.min(start, originalText.length());
int spanEnd = Math.min(start + search.length(),
originalText.length());
highlighted.setSpan(new ForegroundColorSpan(Color.BLUE),
spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = normalizedText.indexOf(search, spanEnd);
}
return highlighted;
}
}
}
MainActivity.java
public class MainActivity extends Activity {
String[] languages = { "C", "C++", "Java", "C#", "PHP", "JavaScript",
"jQuery", "AJAX", "JSON" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> wordList = new ArrayList<String>();
Collections.addAll(wordList, languages);
AutoCompleteAdapter adapter = new AutoCompleteAdapter(this,
android.R.layout.simple_dropdown_item_1line,
android.R.id.text1,wordList);
AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.languages);
acTextView.setThreshold(1);
acTextView.setAdapter(adapter);
}
}
Working like charm!
Enjoy!
I reckon that should be possible, provided you know the index/indices of the character(s) the user typed last. You can then use a SpannableStringBuilder and set a ForegroundColorSpan and BackgroundColorSpan to give the character(s) the appearance of a highlight.
The idea looks somewhat like this:
// start & end of the highlight
int start = ...;
int end = ...;
SpannableStringBuilder builder = new SpannableStringBuilder(suggestionText);
// set foreground color (text color) - optional, you may not want to change the text color too
builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// set background color
builder.setSpan(new BackgroundColorSpan(Color.YELLOW), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// set result to AutoCompleteTextView
autocompleteTextview.setText(builder);
Note that the 'highlight' will remain as long as you don't type another character. You may want to remove the highlight when e.g. the user changes the cursor position in the AutoCompleteTextView, but I'll leave that up to you.
I know it's to late for answering this question , But as I personally battled to find the answer , finally I wrote it myself (with the help of the answer from #MH. ofcourse), so here it is :
First , You have to create a Custom ArrayAdapter :
public class AdapterAustocomplete extends ArrayAdapter<String> {
private static final String TAG = "AdapterAustocomplete";
String q = "";
public AdapterAustocomplete(Context context, int resource, List objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView =
// I'll use a custom view for each Item , this way I can customize it also!
G.inflater.from(getContext()).inflate(R.layout.textview_autocomplete, parent, false);
}
// Lookup view for data population
TextView myTv = (TextView) convertView.findViewById(R.id.txt_autocomplete);
int start = item.indexOf(q);
int end = q.length()+start;
SpannableStringBuilder builder = new SpannableStringBuilder(item);
builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTv.setText(builder);
return convertView;
}
public void setQ(String q) {
this.q = q;
}
}
And in the Code that you want to set the adapter for AutoCompleteTextView ;
AutoCompleteTextView myAutoComplete = findViewById(its_id);
AdapterAustocomplete adapter_autoComplete = new AdapterAustocomplete(getActivity(), 0, items); // items is an arrayList of Strings
adapter_autoComplete.setQ(q);
myAutoComplete.setAdapter(adapter_autoComplete);
Thanks to vadher jitendra I wrote the same and fixed some bugs.
Changed a dropdown layout to own.
Added showing a full list when clicking inside AutoCompleteTextView.
Fixed a bug of freezing the list when showing (added a check for empty string in highlight).
row_dropdown.xml (item layout):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/text1"
style="?android:attr/dropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:ellipsize="marquee"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:singleLine="true"
android:textColor="#333333"
android:textSize="15sp"
tools:text="text"
tools:textAppearance="?android:attr/textAppearanceLargePopupMenu" />
To filter a list when typing we should implement ArrayAdapter. It depends on items (T class). You can later use AutoCompleteAdapter<String> or any data class you like.
AutoCompleteAdapter:
import android.content.Context;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class AutoCompleteAdapter<T> extends ArrayAdapter<T> implements Filterable {
private Context context;
#LayoutRes
private int layoutRes;
#IdRes
private int textViewResId;
private ArrayList<T> fullList;
private ArrayList<T> originalValues;
private ArrayFilter filter;
private LayoutInflater inflater;
private String query = "";
public AutoCompleteAdapter(#NonNull Context context, #LayoutRes int resource, #IdRes int textViewResourceId, #NonNull List<T> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
layoutRes = resource;
textViewResId = textViewResourceId;
fullList = (ArrayList<T>) objects;
originalValues = new ArrayList<>(fullList);
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public T getItem(int position) {
return fullList.get(position);
}
/**
* You can use either
* vadher jitendra method (getView)
* or get the method from ArrayAdapter.java.
*/
// #NotNull
// #Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view = convertView;
// T item = getItem(position);
// Log.d("item", "" + item);
// if (convertView == null) {
// convertView = view = inflater.inflate(layoutRes, null);
// }
// // Lookup view for data population
// TextView myTv = convertView.findViewById(textViewResId);
// myTv.setText(highlight(query, item));
// return view;
// }
#Override
public #NonNull
View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return createViewFromResource(inflater, position, convertView, parent, layoutRes);
}
private #NonNull
View createViewFromResource(#NonNull LayoutInflater inflater, int position,
#Nullable View convertView, #NonNull ViewGroup parent, int resource) {
final View view;
final TextView text;
if (convertView == null) {
view = inflater.inflate(resource, parent, false);
} else {
view = convertView;
}
try {
if (textViewResId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(textViewResId);
if (text == null) {
throw new RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(textViewResId)
+ " in item layout");
}
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
final T item = getItem(position);
text.setText(highlight(query, item.toString()));
// if (item instanceof CharSequence) {
// text.setText(highlight(query, (CharSequence) item));
// } else {
// text.setText(item.toString());
// }
return view;
}
#Override
public #NonNull
Filter getFilter() {
if (filter == null) {
filter = new ArrayFilter();
}
return filter;
}
private class ArrayFilter extends Filter {
private final Object lock = new Object();
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix == null) {
query = "";
} else {
query = prefix.toString();
}
if (originalValues == null) {
synchronized (lock) {
originalValues = new ArrayList<>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<T> list = new ArrayList<>(originalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<T> values = originalValues;
int count = values.size();
ArrayList<T> newValues = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
T item = values.get(i);
if (item.toString().toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
fullList = (ArrayList<T>) results.values;
} else {
fullList = new ArrayList<>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
private static CharSequence highlight(#NonNull String search, #NonNull CharSequence originalText) {
if (search.isEmpty())
return originalText;
// ignore case and accents
// the same thing should have been done for the search text
String normalizedText = Normalizer
.normalize(originalText, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.toLowerCase(Locale.ENGLISH);
int start = normalizedText.indexOf(search.toLowerCase(Locale.ENGLISH));
if (start < 0) {
// not found, nothing to do
return originalText;
} else {
// highlight each appearance in the original text
// while searching in normalized text
Spannable highlighted = new SpannableString(originalText);
while (start >= 0) {
int spanStart = Math.min(start, originalText.length());
int spanEnd = Math.min(start + search.length(),
originalText.length());
highlighted.setSpan(new StyleSpan(Typeface.BOLD), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = normalizedText.indexOf(search, spanEnd);
}
return highlighted;
}
}
}
In order to show dropdown list when clicked inside AutoCompleteTextView we need to override setOnTouchListener as described in https://stackoverflow.com/a/26036902/2914140. Lint also prints warnings, so we have to write a custom view:
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.appcompat.widget.AppCompatAutoCompleteTextView;
/*
Avoids a warning "Custom view `AutoCompleteTextView` has setOnTouchListener called on it but does not override performClick".
*/
public class AutoCompleteTV extends AppCompatAutoCompleteTextView {
public AutoCompleteTV(Context context) {
super(context);
}
public AutoCompleteTV(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoCompleteTV(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
performClick();
}
return super.onTouchEvent(event);
}
#Override
public boolean performClick() {
super.performClick();
return true;
}
}
Then use it in activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.autocompletetextview1.AutoCompleteTV
android:id="#+id/languages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:completionThreshold="1"
android:hint="language"
android:imeOptions="actionNext"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingTop="15dp"
android:paddingRight="10dp"
android:paddingBottom="15dp"
android:singleLine="true"
android:textColor="#333333"
android:textColorHint="#808080"
android:textSize="12sp" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
I use TextInputLayout here for better decoration, in this case we have to add Material Design Components:
in build.gradle:
implementation 'com.google.android.material:material:1.3.0-alpha01'
and in styles.xml:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
...
MainActivity:
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.AutoCompleteTextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
String[] items = {"C", "C++", "Java", "C#", "PHP", "JavaScript", "jQuery", "AJAX", "JSON"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<DataClass> wordList = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
DataClass data = new DataClass(i, items[i]);
wordList.add(data);
}
AutoCompleteAdapter<DataClass> adapter = new AutoCompleteAdapter<>(this,
R.layout.row_dropdown, R.id.text1, wordList);
//adapter.setDropDownViewResource(R.layout.row_dropdown);
AutoCompleteTV acTextView = findViewById(R.id.languages);
acTextView.setThreshold(1);
acTextView.setAdapter(adapter);
acTextView.setText("Java");
acTextView.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
((AutoCompleteTextView) v).showDropDown();
v.requestFocus();
v.performClick(); // Added to avoid warning "onTouch lambda should call View#performClick when a click is detected".
}
return false;
}
);
}
}

how to get data from database with parameter

I'm trying to show a list with the list items from my database having 2 parameters, but the list didn't show.
Here's my query database from php:
$query = mysql_query("SELECT d.model_name from detail_product d join brand b on d.id_brandtype = b.id_brand join biketype t on d.id_biketype = t.id_type where d.id_brandtype = 1 and d.id_biketype=1");
I've set the parameter there.
and here's my DAO:
public class info_xc_dao {
public final static int VIEW_POL_XC = 0;
private static final String URL_VIEW_POL_XC = ServerConfiguration.SERVER_URL
+ "polygon_xc.php";
private int Action;
pol_xc_Result pol_xc_Result;
public info_xc_dao(pol_xc_Result pol_xc_Result) {
// TODO Auto-generated constructor stub
this.pol_xc_Result = pol_xc_Result;
}
public void view_pol_xc() {
Action = VIEW_POL_XC;
new ConnectionHandler(connectionResult, null, URL_VIEW_POL_XC,
ConnectionHandler.GET);
}
public ConnectionResult connectionResult = new ConnectionResult() {
#Override
public void gotResult(String result, String message) {
// TODO Auto-generated method stub
if (result != null) {
switch (Action) {
case VIEW_POL_XC:
try {
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
int response = jsonObject.getInt("result");
if (response != 0) {
JSONArray jsonArray = new JSONArray(
jsonObject.getString("data"));
ArrayList<Entity_Detail_Product> arrayList = new ArrayList<Entity_Detail_Product>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pol_xc = new JSONObject(jsonArray
.get(i).toString());
Entity_Detail_Product ent_detail_product = new Entity_Detail_Product();
ent_detail_product.setModel_name(pol_xc
.getString("model_name"));
arrayList.add(ent_detail_product);
}
pol_xc_Result.gotResult(arrayList, null, Action);
} else {
String error_message = jsonObject
.getString("message");
pol_xc_Result.gotResult(null, error_message,
Action);
}
} catch (JSONException e) {
// TODO: handle exception
pol_xc_Result.gotResult(null,
"Failed parsing data from database. Please try again.. "
+ e.getMessage(), Action);
Log.e("CON ERROR", e.getMessage());
}
}
} else {
pol_xc_Result.gotResult(null, message, Action);
Log.e("CON ERROR", message);
}
}
};
public static abstract class pol_xc_Result {
public abstract void gotResult(Object obj, String message, int action);
}
and here's my activity to call DAO.
public class Information_XC_Activity extends ListActivity {
WebView mWebView;
TextView tv;
private Adapter_DetailPolXC adapterDetailPolXC;
private ListView mainListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_xc);
final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle(getString(R.string.app_name));
int index = getIntent().getIntExtra("text", 0);
mWebView = (WebView) findViewById(R.id.webview_xc);
String temp = "<html><body>" + "<p align=\"justify\">"
+ getString(R.string.xc_info + index) + "</p> "
+ "</body></html>";
mWebView.loadData(temp, "text/html", "utf-8");
ArrayList<Entity_Detail_Product> arraylist = new ArrayList<Entity_Detail_Product>();
adapterDetailPolXC = new Adapter_DetailPolXC(this, R.layout.info_row,
arraylist);
setListAdapter(adapterDetailPolXC);
new info_xc_dao(response).view_pol_xc();
}
pol_xc_Result response = new pol_xc_Result() {
#Override
public void gotResult(Object obj, String message, int action) {
// TODO Auto-generated method stub
// actionBar.setProgressBarVisibility(View.INVISIBLE);
#SuppressWarnings("unchecked")
ArrayList<Entity_Detail_Product> arrayList = (ArrayList<Entity_Detail_Product>) obj;
AlertDialog.Builder builder = new AlertDialog.Builder(
Information_XC_Activity.this);
if (arrayList == null) {
builder.setIcon(R.drawable.alert_warning);
builder.setTitle("Error");
builder.setMessage("Data Not Found !");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
for (Entity_Detail_Product entity_Detail_Product : arrayList) {
adapterDetailPolXC.add(entity_Detail_Product);
}
adapterDetailPolXC.notifyDataSetChanged();
}
}
};
private class Adapter_DetailPolXC extends
ArrayAdapter<Entity_Detail_Product> {
private ArrayList<Entity_Detail_Product> items;
public Adapter_DetailPolXC(Context context, int textViewResourceId,
ArrayList<Entity_Detail_Product> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = (View) layoutInflater.inflate(R.layout.info_xc, null);
}
Entity_Detail_Product adapter_Detail_Product = items.get(position);
if (adapter_Detail_Product != null) {
TextView textView = (TextView) v.findViewById(R.id.tv_test);
if (textView != null)
textView.setText(adapter_Detail_Product.getModel_name());
}
return v;
}
}
and here's my logcat :
09-22 12:41:30.239: W/IInputConnectionWrapper(12808): showStatusIcon on inactive InputConnection
09-22 12:41:33.129: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_brand":"1","1":"Polygon","brand_name":"Polygon"},{"0":"2","id_brand":"2","1":"United Bike","brand_name":"United Bike"},{"0":"3","id_brand":"3","1":"WimCycle","brand_name":"WimCycle"}]}
09-22 12:41:35.009: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_type":"1","1":"Cross Country (XC)","type_name":"Cross Country (XC)"},{"0":"2","id_type":"2","1":"Bicycle Motocross (BMX)","type_name":"Bicycle Motocross (BMX)"},{"0":"3","id_type":"3","1":"Free Ride (FR)","type_name":"Free Ride (FR)"},{"0":"4","id_type":"4","1":"DownHill (DH)","type_name":"DownHill (DH)"},{"0":"5","id_type":"5","1":"DirtJump (DJ)","type_name":"DirtJump (DJ)"},{"0":"6","id_type":"6","1":"Road Bike (RB)","type_name":"Road Bike (RB)"}]}
09-22 12:41:37.219: D/PhoneWindow(12808): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#405440f0 has no id.
09-22 12:41:37.519: I/webclipboard(12808): clipservice: android.sec.clipboard.ClipboardExManager#405d4d40
09-22 12:41:37.839: V/webview(12808): OnSizeChanged: Enter
09-22 12:41:37.859: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_type":"1","1":"Cross Country (XC)","type_name":"Cross Country (XC)"},{"0":"2","id_type":"2","1":"Bicycle Motocross (BMX)","type_name":"Bicycle Motocross (BMX)"},{"0":"3","id_type":"3","1":"Free Ride (FR)","type_name":"Free Ride (FR)"},{"0":"4","id_type":"4","1":"DownHill (DH)","type_name":"DownHill (DH)"},{"0":"5","id_type":"5","1":"DirtJump (DJ)","type_name":"DirtJump (DJ)"},{"0":"6","id_type":"6","1":"Road Bike (RB)","type_name":"Road Bike (RB)"}]}
09-22 12:41:38.169: E/CON ERROR(12808): No value for model_name
09-22 12:41:38.859: V/webview(12808): ZoomScale 3 mPreserveZoom: false
09-22 12:41:38.889: D/CONTEXT(12808): m_mainFrame->editor()->hasComposition not
09-22 12:41:38.959: D/CONTEXT(12808): m_mainFrame->editor()->hasComposition not