I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();
Related
I have image in server url then i'm passing and displaying in to Card. I have done this in android using LoaderImageView library and displaying but in Glass i'm passing the url link to card. But i got this error "The method addImage(Drawable) in the type CardBuilder is not applicable for the arguments (String)"
Code:
public static Drawable drawableFromUrl(String url) {
Bitmap x;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
} catch(MalformedURLException e) {
//Do something with the exception.
}
catch(IOException ex) {
ex.printStackTrace();
}
return null;
}
View view = new CardBuilder(getBaseContext(), CardBuilder.Layout.TITLE)
.setText("TITLE Card")
// .setIcon(R.drawable.ic_phone)
.addImage(drawableFromUrl(link))
.getView();
From the doc, addImage takes Drawable, int, or Bitmap. It doesn't take String.
You can download image using AsyncTask or thread or whatever you like and convert it to Drawable. Then, you can call addImage.
For example:
// new DownloadImageTask().execute("your url...")
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
// yourCardBuilder.addImage(link)
// or start another activity and use the image there...
}
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
I haven't tested the code but hope you get the idea.
Also see:
How to load an ImageView by URL in Android?
Android Drawable Images from URL
Edit:
private Drawable drawableFromUrl(String url) {
try {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return new BitmapDrawable(bitmap);
} catch (IOException e) {
return null;
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
stopSlider();
if(result != null) {
mCardAdapter.setCards(createCard(getBaseContext(), result));
mCardAdapter.notifyDataSetChanged();
}
}
}
See my full example on my GitHub repo. SliderActivity might be helpful for you.
I have written code to filter out new XML elements that have been introduced as part of web service enhancements. The transformation seems to work with small XML but as soon as I increase the size its stops working. Using SoapUI, it simply returns a blank response.
Can anyone help? Do i need to alter the code below to handle large XML?
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
context.PreRequestHandlerExecute += new EventHandler (context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
State state = (State)app.Context.Items["VersionManagerState"];
if (state.ProcessRequest)
{
Stream xslres = Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Concat("TestService.VersionManager.",state.Version, ".xslt"));
if (xslres != null)
{
state.Xsl = new XslCompiledTransform();
state.Xsl.Load(XmlReader.Create(xslres));
app.Context.Response.Filter = new OutputFilterStream(state, app.Context.Response.Filter);
}
}
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
State state = new State();
app.Context.Items["VersionManagerState"] = state;
if (app.Context.Request.Url.AbsolutePath.EndsWith(".asmx") && app.Request.RequestType == "POST")
{
state.ProcessRequest = true;
app.Context.Request.Filter = new InputFilterStream(state, app.Context.Request.Filter);
}
}
I'm implement Google Glass app.
I want to get contacts list from google glass using GDK.
I already tried contacts Api v3 (ContactsService)
but i failed because -
i can't scrolling & tapping(click) pop-up (OK Button) after glass update XE16
-> run to android phone is ok.
i tried
mirror api. device OAuth.... -> no example.. i don't know how...
if you have sample code, As it is also upload. Would you? I'd appreciate that.
here is my code.
public class MainActivity extends Activity
{
private Account[] accounts;
private AccountManager mManager;
private ContactsService mService;
private URL feedUrl;
private final String url = "https://www.google.com/m8/feeds/contacts/default/full";
private final String ACCOUNTS_TYPE = "com.google";
private final String AUTH_TOKEN_TYPE = "cp";
private String mToken;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mManager = AccountManager.get(this);
accounts = mManager.getAccountsByType(ACCOUNTS_TYPE);
Log.d("account", ""+accounts[0]);
mManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>()
{
public void run(AccountManagerFuture<Bundle> future)
{
try
{
mToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
GetTask task = new GetTask();
task.execute(mToken);
}
catch (OperationCanceledException e)
{
e.printStackTrace();
}
catch (AuthenticatorException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}, null);
}
public void createService(String token) throws IOException, ServiceException
{
mService = new ContactsService("contacts_list");
mService.setUserToken(token);
feedUrl = new URL(url);
ContactFeed resultFeed = (ContactFeed)mService.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) getContacts(entry);
}
private class GetTask extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params)
{
try
{
String token = "";
if(params != null)
{
for(String s : params) token += s;
}
createService(token);
}
catch (ServiceException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
public void getContacts(ContactEntry entry) throws ServiceException, IOException
{
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullName = name.getFullName().getValue();
Log.d("name", fullName);
}
}
else Log.d("name", "no name");
if (entry.hasPhoneNumbers())
{
for (PhoneNumber phone : entry.getPhoneNumbers())
{
String phoneNum = phone.getPhoneNumber();
Log.d("phone", phoneNum);
}
}
else Log.d("phone", "no phone");
}
}
I have a class (Not (DAL)) that get's data from DB and give it to me in required format(in specific class format).
Now i need to write a unit test case, but TestContext Data row always return me single row.
I want to fill TestContext by my stored procedure. Please tell me how can i specify stored procedure name.
Thanks in advance.
Here Is Code.
public static List<TextValueField> ExternalDataGet(int providerId)
{
return ListFactory<TextValueField>.Create(Keys.QAT, "[stats].[GetExternalDataV2]", new object[] { providerId }, TextValueField.Factory);
}
public static List<T> Create(string key, string sp, object[] parameters, FactoryDelegate factory)
{
List<T> list = new List<T>();
Database db = DatabaseFactory.CreateDatabase(key);
string connectionString = db.ConnectionStringWithoutCredentials;
using (DbCommand cmd = db.GetStoredProcCommand(sp, parameters))
{
try
{
using (cmd.Connection = db.CreateConnection())
{
cmd.Connection.Open();
cmd.CommandTimeout = 0;
using (DbDataReader reader = cmd.ExecuteReader())
{
try
{
while (reader.Read())
list.Add(factory(reader));
}
finally
{
if (!reader.IsClosed)
reader.Close();
}
}
cmd.Connection.Close();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw new DataAccessException(ex, key, connectionString, sp, parameters);
}
finally
{
if (cmd.Connection != null)
if (cmd.Connection.State == ConnectionState.Open)
cmd.Connection.Close();
}
}
return list;
}
I want to fill TestContext by my stored procedure. Please tell me how can i specify stored procedure name.
This should handle your request.
public static List<TextValueField> ExternalDataGet(int providerId, string storedProc = "[stats].[GetExternalDataV2]")
{
return ListFactory<TextValueField>.Create(Keys.QAT, storedProc, new object[] { providerId }, TextValueField.Factory);
}
I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code