Muzei database doesn't update when I update external JSON - android

I'm in the middle of making a wallpaper app for android and I'm have a problem with Muzei support and hoping someone here can help me see what I'm missing.
I have a JSON file which my app uses to get the wallpaper URLs and display the pictures from. It works fine and it gets the right images. However if I update the JSON with more entries and more images then the Muzei extension still uses the old database. I was thinking that maybe it caches the database and just doesn't update it for whatever reason. The only way to get it to use the updated JSON file is to clear the data of my app and set a different extension in Muzei and the reset Muzei with my extension. Which would not be very user friendly.
Probably just being blind but help would be appreciated.
ArtSource.java:
package com.main.walls.muzei;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.google.android.apps.muzei.api.Artwork;
import com.google.android.apps.muzei.api.RemoteMuzeiArtSource;
import com.google.android.apps.muzei.api.UserCommand;
import com.main.walls.utilities.Preferences;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
import walls.wallpaper.R;
public class ArtSource extends RemoteMuzeiArtSource {
private WallsDatabase wdb;
private ArrayList<WallpaperInfo> wallslist;
private Preferences mPrefs;
private static final String ARTSOURCE_NAME = "Walls";
private static final String JSON_URL = "http://pastebin.com/raw.php?i=VWTzhJ0N";
private static final String MARKET_URL = "https://play.google.com/store/apps/details?id=";
private static final int COMMAND_ID_SHARE = 1337;
public ArtSource() {
super(ARTSOURCE_NAME);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String command = intent.getExtras().getString("service");
if (command != null) {
try {
onTryUpdate(UPDATE_REASON_USER_NEXT);
} catch (RetryException e) {
Log.d("MuzeiArtSource", Log.getStackTraceString(e));
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
wdb = new WallsDatabase(getApplicationContext());
wallslist = new ArrayList<>();
mPrefs = new Preferences(ArtSource.this);
ArrayList<UserCommand> commands = new ArrayList<>();
commands.add(new UserCommand(BUILTIN_COMMAND_ID_NEXT_ARTWORK));
commands.add(new UserCommand(COMMAND_ID_SHARE, getString(R.string.justshare)));
setUserCommands(commands);
}
#Override
public void onCustomCommand(int id) {
super.onCustomCommand(id);
if (id == COMMAND_ID_SHARE) {
Artwork currentArtwork = getCurrentArtwork();
Intent shareWall = new Intent(Intent.ACTION_SEND);
shareWall.setType("text/plain");
String authorName = currentArtwork.getByline();
String storeUrl = MARKET_URL + getResources().getString(R.string.package_name);
String iconPackName = getString(R.string.app_name);
shareWall.putExtra(Intent.EXTRA_TEXT,
getString(R.string.partone) + authorName +
getString(R.string.parttwo) + iconPackName +
getString(R.string.partthree) + storeUrl);
shareWall = Intent.createChooser(shareWall, getString(R.string.share_title));
shareWall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shareWall);
}
}
#Override
protected void onTryUpdate(int reason) throws RetryException {
if (mPrefs.isFeaturesEnabled()) {
if (wallslist.size() == 0)
getWallpapersFromUrl(JSON_URL);
int i = getRandomInt();
String token = wallslist.get(i).getWallURL();
publishArtwork(new Artwork.Builder()
.byline(wallslist.get(i).getWallAuthor())
.imageUri(Uri.parse(wallslist.get(i).getWallURL()))
.token(token)
.viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(wallslist.get(i).getWallURL())))
.build());
scheduleUpdate(System.currentTimeMillis() + mPrefs.getRotateTime());
}
}
private int getRandomInt() {
return new Random().nextInt(wallslist.size());
}
private void getWallpapersFromUrl(String url) {
wallslist.clear();
wallslist = wdb.getAllWalls();
if (wallslist.size() == 0) {
try {
HttpClient cl = new DefaultHttpClient();
HttpResponse response = cl.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() == 200) {
final String data = EntityUtils.toString(response.getEntity());
JSONObject jsonobject = new JSONObject(data);
final JSONArray jsonarray = jsonobject.getJSONArray("wallpapers");
wallslist.clear();
wdb.deleteAllWallpapers();
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WallpaperInfo jsondata = new WallpaperInfo(
jsonobject.getString("author"),
jsonobject.getString("url")
);
wdb.addWallpaper(jsondata);
wallslist.add(jsondata);
}
}
} catch (Exception e) {
Log.d("Wallpapers", Log.getStackTraceString(e));
}
}
}
}
Not sure if I need any other code in here or not and the logcat doesn't say anything, it's as though it's it's working as normal. If you need to see more code just let me know.
Thanks for any help.

Basically I was right and I was just being stupid and missing the simplest thing, it didn't even have anything to do with ArtSource.java.
In WallsDatabase.Java I wasn't updating DATABASE_VERSION. I was leaving it at 1 and so when I updated the app it didn't bother to update the database because the version was the same.
So just change the value of private static final int DATABASE_VERSION = 1 to a higher number and it should work great.
Simple mistake but an easy one to make I guess.

Related

Android get attribute value from xml

I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();

How to know that specific document is present in Cloudant Database using Android App

I have successfully created document in Cloudant database through my Android App. But I can not find a specific document present in Cloudant database. What I have tried is like below....
TabTwo_Fragment.java
package com.example.android02.insightapp11;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DatastoreNotCreatedException;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentNotFoundException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.replication.Replicator;
import com.cloudant.sync.replication.ReplicatorBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* A simple {#link Fragment} subclass.
*/
public class TabTwo_Fragment extends Fragment implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String DATASTORE_MANGER_DIR = "data";
private static final String TASKS_DATASTORE_NAME = "tasks";
Datastore DataStore;
private Replicator PushReplicator, PullReplicator;
DocumentRevision revision;
static final String CLOUDANT_USER = "user_default";
static final String CLOUDANT_DB = "database_name";
static final String CLOUDANT_API_KEY = "api_key";
static final String CLOUDANT_API_SECRET = "api_key_pwd";
long TWITTER_ID = MainActivity.twitterID;
String TWITTER_NAME = MainActivity.userName;
Button btn_submit;
Spinner sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8;
TextView ans_total;
String user = "old";
HashMap<String, String> qa_hashmap;
public TabTwo_Fragment() {
// Required empty public constructor
}
public static TabTwo_Fragment newInstance() {
return new TabTwo_Fragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabtwo_fragment, container, false);
try {
init(rootView);
} catch (DocumentNotFoundException e) {
} catch (DocumentException e) {
} catch (URISyntaxException e) {
}
return rootView;
}
void init(View rootView) throws DocumentException, URISyntaxException {
Log.e("init: ", "in init");
find_view_by_id(rootView);
registerClickEvents();
defaultConfig();
checkForRegisteredUser();
}
void find_view_by_id(View rootView) {
Log.e("find_view_by_id: ", "in find_view_by_id");
btn_submit = (Button) rootView.findViewById(R.id.btn_submit);
sp1 = (Spinner) rootView.findViewById(R.id.sp1);
sp2 = (Spinner) rootView.findViewById(R.id.sp2);
sp3 = (Spinner) rootView.findViewById(R.id.sp3);
sp4 = (Spinner) rootView.findViewById(R.id.sp4);
sp5 = (Spinner) rootView.findViewById(R.id.sp5);
sp6 = (Spinner) rootView.findViewById(R.id.sp6);
sp7 = (Spinner) rootView.findViewById(R.id.sp7);
sp8 = (Spinner) rootView.findViewById(R.id.sp8);
ans_total = (TextView) rootView.findViewById(R.id.ans_total);
}
void registerClickEvents() {
Log.e("registerClickEvents: ", "in registerClickEvents");
btn_submit.setOnClickListener(this);
}
void defaultConfig() {
Log.e("defaultConfig: ", "in defaultConfig");
PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPref.registerOnSharedPreferenceChangeListener(this);
File path = getContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
try {
DataStore = manager.openDatastore(TASKS_DATASTORE_NAME);
setUriPlusReplicators();
} catch (DatastoreNotCreatedException e) {
Toast.makeText(getContext(), "Unable to open Datastore!", Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
Toast.makeText(getContext(), "URI Exception!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
setUriPlusReplicators();
} catch (URISyntaxException e) {
}
}
void setUriPlusReplicators() throws URISyntaxException {
Log.e("setUriPlusReplicators: ", "in setUriPlusReplicators");
URI uri = this.createServerUri();
Log.e("URI: ", "" + uri);
PushReplicator = ReplicatorBuilder.push().from(DataStore).to(uri).build();
PushReplicator.getEventBus().register(this);
PullReplicator = ReplicatorBuilder.pull().to(DataStore).from(uri).build();
PullReplicator.getEventBus().register(this);
}
private URI createServerUri() throws URISyntaxException {
Log.e("createServerUri: ", "in createServerUri");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
}
private URI createServerUri2(long twitterId) throws URISyntaxException {
Log.e("createServerUri2: ", "in createServerUri2");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName + "/_all_docs?", null, null);
}
void checkForRegisteredUser() throws DocumentNotFoundException, DocumentException, URISyntaxException {
BasicDocumentRevision retrieved = DataStore.getDocument(TWITTER_ID + "");
if (user.equals("new")) {
setQuizData(retrieved.getBody().toString());
} else {
newUser();
}
}
void setQuizData(String DataRetrieved) {
Log.e("setQuizData: ", "In setQuizData");
user = "old";
Log.e("DataRetrieved: ", "In " + DataRetrieved);
String[] ANSWERS = getResources().getStringArray(R.array.ans);
try {
JSONObject jsonObject = new JSONObject(DataRetrieved);
JSONObject jsonObject1 = jsonObject.getJSONObject("questions");
String qs1 = jsonObject1.getString("q1");
String qs2 = jsonObject1.getString("q2");
String qs3 = jsonObject1.getString("q3");
String qs4 = jsonObject1.getString("q4");
String qs5 = jsonObject1.getString("q5");
String qs6 = jsonObject1.getString("q6");
String qs7 = jsonObject1.getString("q7");
String qs8 = jsonObject1.getString("q8");
sp1.setSelection(Arrays.asList(ANSWERS).indexOf(qs1));
sp2.setSelection(Arrays.asList(ANSWERS).indexOf(qs2));
sp3.setSelection(Arrays.asList(ANSWERS).indexOf(qs3));
sp4.setSelection(Arrays.asList(ANSWERS).indexOf(qs4));
sp5.setSelection(Arrays.asList(ANSWERS).indexOf(qs5));
sp6.setSelection(Arrays.asList(ANSWERS).indexOf(qs6));
sp7.setSelection(Arrays.asList(ANSWERS).indexOf(qs7));
sp8.setSelection(Arrays.asList(ANSWERS).indexOf(qs8));
} catch (JSONException e) {
}
}
void newUser() {
Log.e("newUser: ", "In newUser");
user = "new";
}
void createDocument() throws DocumentException {
Log.e("createDocument: ", "In createDocument");
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.docId = TWITTER_ID + "";
gatherQAData();
/*HashMap<String, Object> map_main = new HashMap<String, Object>();*/
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<HashMap<String, Object>> arrayTeachers = new ArrayList<>();
map.put("twitter_id", TWITTER_ID + "");
map.put("twitter_name", TWITTER_NAME);
map.put("questions", qa_hashmap);
/*arrayTeachers.add(map);*/
/*map_main.put("user", arrayTeachers);*/
rev.body = DocumentBodyFactory.create(map);
revision = DataStore.createDocumentFromRevision(rev);
PushReplicator.start();
}
void updateDocument() {
Log.e("updateDocument: ", "In updateDocument");
}
void gatherQAData() {
Log.e("gatherQAData: ", "In gatherQAData");
qa_hashmap = new HashMap<String, String>();
String a1, a2, a3, a4, a5, a6, a7, a8;
a1 = sp1.getSelectedItem().toString();
a2 = sp2.getSelectedItem().toString();
a3 = sp3.getSelectedItem().toString();
a4 = sp4.getSelectedItem().toString();
a5 = sp5.getSelectedItem().toString();
a6 = sp6.getSelectedItem().toString();
a7 = sp7.getSelectedItem().toString();
a8 = sp8.getSelectedItem().toString();
qa_hashmap.put("q1", a1);
qa_hashmap.put("q2", a2);
qa_hashmap.put("q3", a3);
qa_hashmap.put("q4", a4);
qa_hashmap.put("q5", a5);
qa_hashmap.put("q6", a6);
qa_hashmap.put("q7", a7);
qa_hashmap.put("q8", a8);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_submit:
if (user.equals("new")) {
try {
createDocument();
} catch (DocumentException e) {
}
} else {
updateDocument();
}
break;
default:
}
}
}
I can get the document which is stored in DataStore. But I am unable to get document stored in Cloudant database.
FYI: I am finding document in checkForRegisteredUser method.
Yes, I have done it. Below is my code for checkForRegisteredUser method of TabTwo_Fragment.java
void checkForRegisteredUser() {
String url = "https://your_cloudant_user_name.cloudant.com/" + DB_NAME + "/" + DOC_ID;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response.toString().length() > 0) {
setQuizData(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
newUser();
}
});
requestQueue.add(jor);
Here is s Official Documentation LINK.
Here DOC_ID is the id of document that you want to check. Hope this will help to somebody.
What happens in Cloudant is that there are already two fields by default given by cloudant to each document namely _id and _rev where _id acts as primarykey for indexing. So there will be a default index created by cloudant on the _id field. If you already have these fields in your document than cloudant won't insert extra _id and _rev.
Now you can have this _id field in your document and set it according to yourself or let cloudant set it. But when you are not setting it than you won't be able to query Cloudant on the primary index because you don't know the _id of the document.
So to search or find on basis of some other field like the twitter_id as you have stored you have to create one more index than you'll be able to search/find according to that.
we can create index in java using the function provided by cloudant api
public void createIndex(java.lang.String indexName,
java.lang.String designDocName,
java.lang.String indexType,
IndexField[] fields)
or If you are assigning _id in your function than you can simply call a function
db.contains(doc_id);
which is a lot easier as you don't need to create any index and using default index.
EDIT-1
So the db here is the database instance you have acquired.
Database db=client.database(db_name,create_flag);
where create_flag is a boolean to if the database should be created if not existed so true means yes create false means no don't create if not there.
and client is CloudantClient object.
But alternatively you can call createDB also if you know the db is not there. You can do it as follow
Database db=client.createDB("DBNAME");
How to get a CloudantClient is dependent on the version of cloudant api you are using. for ex 1.0.1 is different from the latest.
in version 1.0.1 you do it as follow
CloudantClient client=new CloudantClient(URL_OF_YOUR_CLOUDANT,USERNAME,PASSWORD);
But in latest release they use
CloudantClient client=ClientBuilder.url(new URL("your url")).username("your username string").password("your password").build();
SO I don't know why you were not able to find createIndex. I suppose you are unable to find Cloudant-api javadocs .Just google for Cloudant javadocs or check this github
GitHub link

Unable to get output from Pd library and Android app

I am trying to get a simple Android app working with the Pd library I have integrated within my eclipse environment.
I have successfully build and compiled an example project called "CircleOfFifths" which proves that the library has been integrated fine in eclipse.
I am using cordova/phonegap and trying to create a plugin for libpd. All the plugin communication with the javascript file on the front-end is working fine.
The code seems to initialise and load the patch fine. It also goes into the play() method but I don't get any output. I am expecting to hear the sine wave.
I followed this tutorial on YouTube.
My code can be viewed here, and the patch is here.
Can anyone help me figure out where I can be going wrong?
My ultimate objective is to use a live audio from microphone and process that audio and return immediately with applied Pd patch (patch is ready and created for this) but before I go to that stage I want to make sure that I get some sort of output from the existing patch. Same patch as the one above in the YouTube tutorial.
package com.test.libpd;
import java.io.File;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.puredata.android.io.AudioParameters;
import org.puredata.android.io.PdAudio;
import org.puredata.android.utils.PdUiDispatcher;
import org.puredata.core.PdBase;
import org.puredata.core.utils.IoUtils;
import android.content.Context;
import android.util.Log;
import com.sgil.libpddemo.R;
public class Libpd extends CordovaPlugin {
private static final String TAG = "libpd_plugin";
private Exception exception;
private Context AppContext;
private PdUiDispatcher dispatcher;
private static final int MIN_SAMPLE_RATE = 44100;
public Libpd() { // constructor
}
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Log.v(TAG, "Init LIBPD PLUGIN");
}
public boolean execute(final String action, final JSONArray args,
final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
// #SuppressLint("NewApi")
public void run() {
Log.v(TAG, "Plugin received:" + action);
Libpd libpd = new Libpd();
libpd.AppContext = getApplicationContext();
try {
libpd.initPd(libpd.AppContext);
libpd.loadPatch(libpd.AppContext);
} catch (IOException e) {
Log.e(TAG, e.toString());
// libpd.finish();
}
if (action.equals("playRec")) {
// MediaRecordMethod mediaRecordMethod = new
// MediaRecordMethod(action);
// mediaRecordMethod.init();
libpd.play();
}
if (action.equals("stopRec")) {
libpd.onPause();
}
if (action.equals("startRec")) {
libpd.record("start");
libpd.play();
}
}
});
return true;
}
private void initPd(Context ctx) throws IOException {
AudioParameters.init(ctx);
// Configure the audio glue
int sampleRate = AudioParameters.suggestSampleRate();
int srate = Math.max(MIN_SAMPLE_RATE, AudioParameters.suggestSampleRate());
// int sampleRate = 64;
int inpch = AudioParameters.suggestInputChannels();
int outpch = AudioParameters.suggestOutputChannels();
PdAudio.initAudio(srate, 0, outpch, 8, true);
// Create and install the dispatcher
dispatcher = new PdUiDispatcher();
PdBase.setReceiver(dispatcher);
}
private void loadPatch(Context ctx) throws IOException {
File dir = ctx.getFilesDir();
Log.v(TAG, "path:" + dir.getAbsolutePath().toString());
//File dir = new File("/sdcard/mypatches");
IoUtils.extractZipResource(
ctx.getResources().openRawResource(R.raw.simplepatch), dir, true);
File patchFile = new File(dir, "simplepatch.pd");
PdBase.openPatch(patchFile.getAbsolutePath());
//PdAudio.startAudio(ctx);
//this.record("start");
}
private void record(String startorStop) {
if (startorStop.equals("start")) {
PdBase.sendSymbol("recordfilename", "x.aiff");
PdBase.sendBang("openfile");
PdBase.sendBang("record");
} else {
PdBase.sendBang("stoprecording");
}
}
// play back the last recording from the file called 'recorded'
public void play() {
//PdBase.sendSymbol("playfilename", "x.aiff");
//PdBase.sendBang("readfile");
//PdBase.sendBang("play");
Float val = 1.0f;
PdBase.sendFloat("onOff", val);
}
protected void onPause() {
PdAudio.stopAudio();
PdAudio.release();
PdBase.release();
}
}
your code never starts the audio-processing.
For whatever reasons youhave uncommented the line
PdAudio.startAudio(ctx)

Android async task causing black screen

I'm using an async task to download a json string from my server. This is the code I'm using:
How I use it is, first I open the profile activity, then on the oncreate event on the profile activity, I call this async task to get the information. When this finishes it calls a function on the profile activity using its context to display the information. If some error occurred, then I call the finish function on the activity and display a message.
The problem is, the first time when I visit the profile activity, it works fine, then the second time it goes into a black screen. The interesting thing is I can press back and it will end the black screen but go back to previous activity (the one where I click the button to open the profile activity).
Does anyone know whats the problem here?
Thanks.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import sord.http.Http;
import sord.ids_connect.Activity_Profile;
import sord.ids_connect.R;
import sord.object.User;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
/*
* This asynchronous task gets profile data.
*
*/
public class Async_get_profile extends AsyncTask<String, Void, Pair<String,Integer>> {
Activity_Profile callerContext = null;
ProgressDialog progressDialog = null;
int targetID;
public Async_get_profile(Activity_Profile callerContext, int targetID) {
this.callerContext = callerContext;
this.targetID = targetID;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog((Context) callerContext);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Pair<String,Integer> doInBackground(String... params) {
List<NameValuePair> urlValues = new ArrayList<NameValuePair>();
urlValues.add(new BasicNameValuePair("taskID", "5"));
urlValues.add(new BasicNameValuePair("userID", Integer.toString(User.currentUser.id, 10)));
urlValues.add(new BasicNameValuePair("targetID", Integer.toString(targetID, 10)));
Pair<String,Integer> response = Http.GetHTTPResponse(((Context) callerContext).getResources().getString(R.string.host), urlValues);
return response;
}
#Override
protected void onPostExecute(Pair<String,Integer> responsePair) {
try {
JSONObject object = Http.ValidateObjectResponse(((Context) callerContext), responsePair);
if (object != null) {
String firstname = object.getString("firstname");
String lastname = object.getString("lastname");
String password = object.getString("password");
String email = object.getString("email");
String phone = object.getString("phone");
String website = object.getString("website");
String status = object.getString("status");
String biotext = object.getString("biotext");
int roldId = object.getInt("role_id");
String datejoined = object.getString("datejoined");
String datelastactive = object.getString("datelastactive");
int active = object.getInt("active");
String picURL = object.getString("picURL");
if (targetID == User.currentUser.id) {
User.currentUser.firstName = firstname;
User.currentUser.lastName = lastname;
User.currentUser.password = password;
User.currentUser.emailAddress = email;
User.currentUser.phoneNumber = phone;
User.currentUser.websiteLink = website;
User.currentUser.statusText = status;
User.currentUser.bioText = biotext;
User.currentUser.dateJoined = datejoined;
User.currentUser.dateLastActive = datelastactive;
User.currentUser.picURL = picURL;
callerContext.ProfileCallback(User.currentUser);
} else {
User user = new User(
false,
targetID,
firstname,
lastname,
password,
email,
phone,
website,
status,
biotext,
roldId,
datejoined,
datelastactive,
active,
picURL
);
callerContext.ProfileCallback(user);
}
} else {
callerContext.finish();
}
} catch (Exception e) {
Log.d("ERROR", e.getMessage());
callerContext.finish();
}
progressDialog.dismiss();
}
}
EDIT:
Logcat
log.txt

Using YouTube Data Api in Android

Am trying to use YouTube Data Api in my android app. When i try to run it as a java project, it runs fine without any errors. But when i try to do the same thing in my android application , the application force closes. Here is the output from logcat and my code.
OUTPUT FROM LOGCAT
01-05 00:13:17.198: E/AndroidRuntime(627): FATAL EXCEPTION: main
01-05 00:13:17.198: E/AndroidRuntime(627): java.lang.ExceptionInInitializerError
01-05 00:13:17.198: E/AndroidRuntime(627): at com.example.allinonedata.YouTubeManager.retrieveVideos(YouTubeManager.java:29)
...
01-05 00:13:17.198: E/AndroidRuntime(627): Caused by: java.lang.NoClassDefFoundError: com.google.gdata.data.media.MediaSource
HERE IS THE CODE
mainactivity.java
package com.example.allinonedata;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
String clientID = "JavaCodeGeeks";
String textQuery = "nexus 4";
int maxResults = 1;
boolean filter = true;
int timeout = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubeManager ym = new YouTubeManager(clientID);
try{
List<YouTubeVideo> videos = ym.retrieveVideos(textQuery, maxResults, filter, timeout);
for (YouTubeVideo youtubeVideo : videos) {
System.out.println(youtubeVideo.getWebPlayerUrl());
System.out.println("Thumbnails");
for (String thumbnail : youtubeVideo.getThumbnails()) {
System.out.println("\t" + thumbnail);
}
System.out.println(youtubeVideo.getEmbeddedWebPlayerUrl());
System.out.println("**************************************************");
}
}
catch(Exception e)
{
}
}
}
youtubemanager.java
package com.example.allinonedata;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaContent;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
public class YouTubeManager {
private static final String YOUTUBE_URL = "http://gdata.youtube.com/feeds/api/videos";
private static final String YOUTUBE_EMBEDDED_URL = "http://www.youtube.com/v/";
private String clientID;
public YouTubeManager(String clientID) {
this.clientID = clientID;
}
public List<YouTubeVideo> retrieveVideos(String textQuery, int maxResults,
boolean filter, int timeout) throws Exception {
YouTubeService service = new YouTubeService(clientID);
service.setConnectTimeout(timeout); // millis
YouTubeQuery query = new YouTubeQuery(new URL(YOUTUBE_URL));
query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);
query.setFullTextQuery(textQuery);
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
query.setMaxResults(maxResults);
VideoFeed videoFeed = service.query(query, VideoFeed.class);
List<VideoEntry> videos = videoFeed.getEntries();
return convertVideos(videos);
}
private List<YouTubeVideo> convertVideos(List<VideoEntry> videos) {
List<YouTubeVideo> youtubeVideosList = new LinkedList<YouTubeVideo>();
for (VideoEntry videoEntry : videos) {
YouTubeVideo ytv = new YouTubeVideo();
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
String webPlayerUrl = mediaGroup.getPlayer().getUrl();
ytv.setWebPlayerUrl(webPlayerUrl);
String query = "?v=";
int index = webPlayerUrl.indexOf(query);
String embeddedWebPlayerUrl = webPlayerUrl.substring(index+query.length());
embeddedWebPlayerUrl = YOUTUBE_EMBEDDED_URL + embeddedWebPlayerUrl;
ytv.setEmbeddedWebPlayerUrl(embeddedWebPlayerUrl);
List<String> thumbnails = new LinkedList<String>();
for (MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
thumbnails.add(mediaThumbnail.getUrl());
}
ytv.setThumbnails(thumbnails);
List<YouTubeMedia> medias = new LinkedList<YouTubeMedia>();
for (YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) {
medias.add(new YouTubeMedia(mediaContent.getUrl(), mediaContent.getType()));
}
ytv.setMedias(medias);
youtubeVideosList.add(ytv);
}
return youtubeVideosList;
}
}
The google-api-java-client (which does have Android support, unlike the gdata-client) didn't previously support the Youtube Data API, but with the release of v3 this is now rectified; there is good Youtube support now with this client that should provide you what you need. See here for details and code samples:
https://developers.google.com/api-client-library/java/apis/youtube/v3
and also to Getting started Guide here
https://developers.google.com/youtube/v3/getting-started

Categories

Resources