I am having some problems with my phone camera (I am using Sony Xperia Z1 Compact) because the camera is always on Landscape mode when I launch it via the intent and therefore the photo is rotated when taken in portrait mode. This issue doesn't exist on Nexus 5. How can I solve it ? The exif returns always 0 because it's locked on landscape
mercredi 6 mai 2015
Google Places autocomplete Android - Not working
I am new to Android App development. I followed this toturial to write a simple Google Places autocomplete Android App, but it does not return any suggestions when I start typing in the app; it gives NativeCrypto error in LogCat when I write anything in the autocomplete textview. Here is my code:
package com.example.newxyz;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
public class GooglePlacesAutocompleteActivity extends Activity implements OnItemClickListener {
private static final String LOG_TAG = "Google Places Autocomplete";
private static final String PLACES_API_BASE = "http://ift.tt/1g2WBZ4";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "AIzaSyAujQlZ1Jj64NAHMoynXjI253MVRzGW09w";
private static final String True = "true";
private static final String language = "en";
AutoCompleteTextView autoCompView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?sensor=" + True);
sb.append("&key=" + API_KEY);
sb.append("&language" + language);
//sb.append("&components=country:gr");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public String getItem(int index) {
return resultList.get(index);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
Here is my LogCat error:
05-04 13:16:27.705: E/NativeCrypto(9312): ssl=0x611c0a20 cert_verify_callback x509_store_ctx=0x62625940 arg=0x0
05-04 13:16:27.705: E/NativeCrypto(9312): ssl=0x611c0a20 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
- I have enabled Google Places API for Android in console.developers.google.com
- I am using a Browser key for my app
- I have looked for answers to my problem and haven't found any relevant answer yet
- I have given Internet permissions in the Menifest file
- In Overview of the Developer Console, the Graph is showing the requests, which means requests are made but there is no response.
Any help would be much appreciated. Thanks
Toolbar bug with method setTitle
I am using this two methods in my toolbar:
toolbar.setTitleTextColor(getResources().getColor(R.color.ColorPrimary));
getSupportActionBar().setTitle("title");
The reason for using getSupportActionBar is because toolbar.setTitle("title"); is not working.
This is a bug?
Android Studio combine 2 .aar into one
I have an Android Studio library project which depends on another library project.
The top project depends on code and resources from the second library project.
When using just the top library-project .aar in a client app, the resources from the second library project are not found.
So do we have to always use 2 .aar files instead of one in such a situation?
Parse for Android: ParseInstallation.getCurrentInstallation().get(KEY_DEVICE_TOKEN) returns null
Parse for Android: Trying to get a device token in Parse but it keeps returning null. This code was working about 6 months back but lately have noticed this issue. Using the device token to subscribe to Parse later on. It just gets stuck in the while loop.
private static final String KEY_DEVICE_TOKEN = "deviceToken";
boolean isTokenReady = false;
while (!isTokenReady) {
String deviceToken = (String) ParseInstallation.getCurrentInstallation().get(KEY_DEVICE_TOKEN);
if (!StringHelper.isNullOrEmpty(deviceToken)) {
subscribe(deviceToken);
isTokenReady = true;
} else {
sleep(1000);
}
}
ParsePush.subscribeInBackground("pushtoken_" + deviceToken);
Error:android-apt-compiler: Cannot run program "sdk_path/build-tools/21.1.2/aapt": java.io.IOException: error=13, Permission denied
I'm using Intellij IDEA 14.1.2, java version "1.6.0_45" and OS Ubuntu 14.04 32bit, Showing this error during execution.
Error:android-apt-compiler: Cannot run program "sdk_path/build-tools/21.1.2/aapt": java.io.IOException: error=13, Permission denied
May I know you how can I solve this error?
Test events were not received - Android Studio
I have no idea how to test and I was following a tutorial.I am trying to run:
package name.company.sunshine.app.data;
import android.test.AndroidTestCase;
public class TestPractice extends AndroidTestCase {
/*
This gets run before every test.
*/
@Override
protected void setUp() throws Exception {
super.setUp();
}
public void testThatDemonstratesAssertions() throws Throwable {
int a = 5;
int b = 3;
int c = 5;
int d = 10;
assertEquals("X should be equal", a, c);
assertTrue("Y should be true", d > a);
assertFalse("Z should be false", a == b);
if (b > d) {
fail("XX should never happen");
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
}
but I get somewhere in the bottom left corner, in the console Test events were not received. What am I doing wrong ? Should I run something else ?
GCC fails with no message when using precompiled headers
I am trying to use precompiled headers in my rather large android NDK project. The precompiled header builds correctly, and I get the gch file that I can see is being used when I compile the source file. However, the "make" command fails with Error 1, but GCC doesn't tell me why it failed:
../Makefile:##: recipe for target '...' failed
make[1]: *** [...] Error 1
make[1]: Leaving directory
I have also found that rearranging the headers such that my precompiled header is smaller (around ~128MB) it works. The original size of my pch was ~173MB. I know for VS, there is a /Zm option that allows you to change the size limit of a precompiled header, but I can't find such an option for GCC, nor can I find any indication that such a limit exists for GCC.
Does anyone have any ideas as to why my build will fail and any ideas on how I can work around it?
Thanks in advance.
EDIT:
Some clarifications:
1) The code DOES compile if I don't use PCH, so it's not like I'm missing libraries or files or anything like that.
2) I DO get GCC error messages when the compilation fails normally. It's only this one case where I don't see any.
Toast "Press back again to close" gives error when pressing back too often
My goal:
When a visitor goes back to the first page of my app, a toast appears to let the visitor know that he can press the back button again within 3 seconds to close the Android app.
Specific problem:
When you went back to the first page and the toast appears, the code works fine when you press back only once but when the toast appears and you press back more than one time, the following error message appears: "(appname) has stopped".
Does anyone know what causes this error message and how I can solve this?
MainActivity.java file:
// Open previous opened link from history on webview when back button pressed
private Boolean exit = false;
@Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
if (exit)
this.finish();
else {
Toast.makeText(this, "Press again to exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
}
"unimplemented Not counting objects in space" What means this Android log?
By Log tag: art
By Log message:
static void art::Dbg::DdmSendHeapSegments(bool) unimplemented Not counting objects in
space SpaceTypeImageSpace begin=0x7097f000,end=0x712f4000,size=9MB,name="/data/dalvik-
cache/x86/system@framework@boot.art"]
Hello. I have question with it Android log. What is it? Maybe someone know?
Google Play Store - Top New Games List
We published our first mobile game 5 days ago and it has almost 10 000 downloads so far and 4.9 rating. I am curious why the game is not presented in top new apps chart while there are many games in this chart with fewer downloads and lower rating.
Is this connected with the fact that the game was released only 5 days ago?
One document about that which I found is:
but the only accurate point here is that the game has to be less than 30 days old in order to get to top new games chart.
inflate view returns the old inflated result
I try to inflate a layout multiple times to be inserted inside another layout. Here is the code:
View oldView = null;
for (ProfileServiceCategory.ProfileService service : profileServiceCategory.getServices()) {
View view = LayoutInflater.from(context)
.inflate(R.layout.profile_service_list_item, viewHolder.rootView);
if(oldView == view) {
Log.d("test", "Error");
}
oldView = view;
TextView serviceName = (TextView) view.findViewById(R.id.profile_services_name);
serviceName.setText(service.getServiceValue());
}
The problem that I'm facing is the view variable that is being returned by inflate method is always the first inflated view. To be clear I added a Log.d , if everything worked as expected it should have been never called but it does hit.
I checked the view hierarchy and I can conform that new views in fact has been added to rootView but the reference that I get is for older view.
the grid should display at least two columns , according to screen size can display more
I have GridView, the grid should display at least two columns , according to screen size can display more.
<GridView
android:id="@+id/fragment_grid_gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="300dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
I don't know, how to do this.
Need an android code to build background service that can deactivate all the installed apps of a device
Let me know whether is der any background service in android java code available to disable or enable all the installed apps in a mobile device?
ESC command printing android bold
I have an android app that prints via bluetooth but I have an issue sending an ESC command for a bold character.
StringBuilder builder = new StringBuilder();
builder.append("Data Ordine: " + mDetailsOrderList.get(0).date_add + "\n");
builder.append("\x1B\x21\x08"+"Riferimento: " + "\x1B\x21\x00" + mDetailsOrderList.get(0).reference + "\n");
\x1B\x21\x08 able bold ESC ! 08
\x1B\x21\x00 diable ESC ! 00
For example, I want riferimento as bold but don't accept this syntax..illegal character "/"
Could you help me solve this issue please?
Preview ViewSwitcher in AndroidStudio
Is there an easy way to switch between the displayed view in a ViewSwitcher in the Android Studio preview, or is the only way to swap out the XML for the sub-views one at a time?
Android AudioFlinger Error: No More Overflow Buffers when playing video
I am trying to play a series of videos back-to-back in a never ending loop. For some reason, after the app has been running for several hours, my videos begin to stutter and this error shows up repeatedly in the logcat:
W/AudioFlinger( 6310): OutputTrack::write() 0xb36e8008 thread 0xb6ffebc8 no more overflow buffers
What exactly does this mean and how can I prevent this from occurring. I would like the app to be able to run indefinitely without the video issues popping up.
Calling a method in a fragment in a FragmentStatePagerAdapter from the activity that created it
I have an activity that has a navigation drawer and a Fragment state adapter. When ever I click something in the navigation drawer I am passing that info to the mainactivity via a interface.And then I am passing that data to the main fragment which is in Fragmentstateadapter. The problem is when ever the screen rotates I get a null pointer exception for the main fragment.`
public class MainActivity extends ActionBarActivity implements RightDrawerRecyclerAdapter.Filters,
LeftDrawerFragment.MenuSection,CommonAsyncTask.ServerData {
private static final String TAG = MainActivity.class.getSimpleName();
public MainFragment mMainFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
ScreenSlidePagerAdapter pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
@Override
public void getMenuSelection(int selection) {
Log.d(TAG,"getMenuSelection->"+selection);
mMainFragment.getMenuSelection(selection);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
Log.d(TAG, "in screenslide");
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
Log.d(TAG, "in returning MainFragment");
mMainFragment=new MainFragment();
return mMainFragment;
} else {
return new MapViewFragment();
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "List";
} else {
return "Map";
}
}
}}
So getMenuSelection is the method from the interface in navigation drawer. Then I have a method with the same name in my main fragment in MainFragment.So when ever I select something in the navigation drawer I can change contents in the main fragment but when ever I turn my screen a new instance of MainFragment is getting created and getItem(int position) is not getting trigged so my MainFragment object is null and now I cant pass data from my navigation drawer to main fragment.I tried making MainFragment object as static and that created problems in my MainFragment class.
So how can I get back the same MainFragment object even when the screen is turned. Or is there any better way to pass data between navigation drawer fragment and a fragment in FragmentState adapter
How run android on genymotion
After installing genymotion I try to start this app. But genymotion says - On your computer not launched Virtual Machine...
I open Virtual Box and try to creating new Linux, Ubuntu(64) machine. I start this machine and fetched more and more errors from virtual box (i not understand these errors).
How to launch genymotion, without these all problems. Light way?
мая 6 20:28:09 [Genymotion] [Error] VBoxManage ("hostonlyif", "create") returns 1
мая 6 20:28:09 [Genymotion] [Error] Output command: "0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to create the host-only adapter
VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: failed to open /dev/vboxnetctl: No such file or directory
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterface, interface IHostNetworkInterface
VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)" at line 66 of file VBoxManageHostonly.cpp"
мая 6 20:28:09 [Genymotion] [Error] failed to create host only interface
мая 6 20:28:09 [Genymotion] [Error] "Fail to load vboxmanage plugin from /opt/genymotion/plugins/"
мая 6 20:28:09 [Genymotion] [Error] VM Engine failed to load
мая 6 20:28:09 [Genymotion] [Error] Unable to find VM Engine. Plugin loading aborted.
Intro animation for android app
I want to add an introduction "animation" to my application (which has a Navigation Drawer) to "teach" people how to use it (basically how to open the drawer, close it etc)
How can I do it? I want it to be interactive with the app itself: at the beginning I want it to show a "hand" pulling the navdrawer and then it waits until the drawer has been opened, then it performs other stuff. I have seen it in some applications but I don't know what to look for achieve it.
I'll appreciate any kind of help, thanks
Fade in/fade out text with canvas
I am wondering what is the best approach for adding animation to a graphics paint object on a canvas. In my case, what is the best way to fadein/fadeout text that is being drawn on a canvas?
Thanks
How to implement custom CardScrollView on Google Glass?
I try'd to use a CardScrollView instead of a single View.I can set cards(with custom layouts) successfully with my code.I need to change the values of my TextFields when a new Message arrived from my LocalBroadcastReceiver. Do you have some idea how/where I can solve it?
Here are some code snippets from my project.
This is the onCreate method in the activity that the CardScrollView implements.
private List<Integer> cards;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
createCards();
xDataScrollView = new CardScrollView(this);
xDataScrollView.setAdapter(new XDataCardScrollAdapter(cards, getLayoutInflater()));
xDataScrollView.activate();
setContentView(xDataScrollView);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("newMqttData"));
...
}
With the following createCards() Method
public void createCards() {
cards = new ArrayList<Integer>();
cards.add(R.layout.x_general);
cards.add(R.layout.x_temperatures);
}
And this CardScrollAdapter.
public class XDataCardScrollAdapter extends CardScrollAdapter{
private List<Integer> cards;
private LayoutInflater inflater;
private SingletonData data;
public XDataCardScrollAdapter(List<Integer> cards, LayoutInflater inflater){
this.cards = cards;
this.inflater = inflater;
this.data = SingletonData.getInstance();
}
@Override
public int getCount() {
return cards.size();
}
@Override
public Object getItem(int i) {
return cards.get(i);
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return inflater.inflate(cards.get(i),viewGroup,false);
}
@Override
public int getPosition(Object o) {
return cards.indexOf(o);
}
}
Edit I was able to have some values in both defined cards at the startup of the activity but I'm still unsure how to update the data from my broadcast receiver. Here my modified getView method in XDataCardScrollAdapter. Even dont know if that is an acceptable solution or that something can go wrong here.
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = inflater.inflate(cards.get(i), viewGroup);
}
if(i == 0){
TextView textView_speed = (TextView) view.findViewById(R.id.textView_speed);
textView_speed.setText(data.getSpeed());
... more values here
}else if(i==1){
TextView textView_temperatureValue = (TextView) view.findViewById(R.id.textView_temperatureValue);
textView_temperatureValue.setText(data.getTemperature());
...more values here
}
return view;
}
Creating a Gridview for a word search
I am trying to create a word search using a gridview but I'm unsure how to add rows from a JSONArray, but my app keeps crashing at this point and also at gridView.addView(tableRow);
This is my new puzzle class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
public class NewPuzzleActivity extends Activity implements OnRetrieveHTTPData {
//word search data
String[] rows;
String[] words;
char[] letters;
//variables for the grid creation
int letterID = 0;
int rowID = 0;
//found words by the user
String[] wordsFound;
int[] rowFound;
int[] columnFound;
int[]directionFound;
// objects within the game *miscellaneous properties*
boolean firstLetterSelected = false;
int numOFLettersSelected = 0;
int[] lettersSelected;
int[] rowsSelected;
int[] columnsSelected;
String selectedString = "";
int directionSelected = 0;
int lastLetterSelected = -1;
String date;
GridView gridView;
TextView textView;
Toast toast;
public NewPuzzleActivity(){
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
gridView = (GridView) findViewById(R.id.gridView1);
Intent intent = getIntent();
if(intent.hasExtra("rows")){
// initialize the data
rows = intent.getExtras().getStringArray("rows");
addRows();
stringArrayToCharArray();
fillGrid();
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
if(intent.hasExtra("words")){
words = intent.getExtras().getStringArray("words");
wordsFound = new String[words.length];
rowFound = new int[words.length];
columnFound = new int[words.length];
directionFound = new int[words.length];
fillWords();
}
if(intent.hasExtra("date")){
date = intent.getExtras().getString("date");
//textView = (TextView)findViewById(R.id.Title);
//textView.append(date);
}
}
public void letterButonClick(View view){
if(toast != null){
toast.cancel(); // cancel toast message to prevent multiple toast messages
}
TextView textView1 = (TextView) findViewById(view.getId());
textView1.setTextColor(Color.RED);
//works out the column number of the selected letter(s)
columnsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[numOFLettersSelected] == 0) columnsSelected[numOFLettersSelected] = rows.length;
//works out the row number of the selected letter(s)
rowsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())/ rows.length)+1;
if(rowsSelected[numOFLettersSelected] == 0) rowsSelected[numOFLettersSelected] = rows.length;
//fixes the last column
if(columnsSelected[numOFLettersSelected] == rows.length) rowsSelected[numOFLettersSelected]-=1;
lettersSelected[numOFLettersSelected] = Integer.parseInt(view.getTag().toString()) + 4999;
Log.i("Selected Column", Integer.toString(columnsSelected[numOFLettersSelected]));
Log.i("Selected Row", Integer.toString(rowsSelected[numOFLettersSelected]));
if(!firstLetterSelected){
firstLetterSelected = true;
//resets the selected string
selectedString = textView1.getText().toString();
numOFLettersSelected = 1;
}else{
//adds letters to selected string
selectedString += textView1.getText().toString();
//compares to the last letter to work out the direction
if(columnsSelected[numOFLettersSelected] +1 == columnsSelected[numOFLettersSelected - 1] &&
rowsSelected[numOFLettersSelected] +1 == rowsSelected[numOFLettersSelected - 1]){
//direction left / down
directionSelected = 0;
Log.i("Direction", "0");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is down
directionSelected = 1;
Log.i("Direction", "1");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected] - 1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]){
//direction is right-down
directionSelected = 2;
Log.i("Direction", "2");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is left
directionSelected = 3;
Log.i("Direction", "3");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is right
directionSelected = 4;
Log.i("Direction", "4");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]){
//direction is left-up
directionSelected = 5;
Log.i("Direction", "5");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is up
directionSelected = 6;
Log.i("Direction", "6");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]) {
//direction is right-up
directionSelected = 7;
Log.i("Direction", "7");
checkWordFound();
}else{
// not a letter within/ around the the first letter selected, reset any selected letters
//deselect words and select a new letter to starr again
//selected string reset
selectedString = textView1.getText().toString();
for(int i : lettersSelected){
try{
TextView letters = (TextView)findViewById(i);
letters.setTextColor(Color.BLACK);
i++;
}catch (Exception e){
//break
Toast.makeText(getApplication(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
// new letter to be selected
columnsSelected[0] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[0] == 0) columnsSelected[0] = rows.length;
rowsSelected[0] = (Integer.parseInt(view.getTag().toString()) / rows.length)+1;
if(rowsSelected[0] == 0) rowsSelected[0] = rows.length;
if(columnsSelected[0] == rows.length) rowsSelected[0] -= 1;
lettersSelected[0] = Integer.parseInt(view.getTag().toString()) + 4999;
textView1.setTextColor(Color.RED);
}
numOFLettersSelected++;
Log.i("Selected TEXT", selectedString);
}
lastLetterSelected = Integer.parseInt(view.getTag().toString());
}
private void fillGrid(){
int LetterChars = 0;
for(int i = 0; i < rows.length * rows.length; i++){
if(LetterChars >= rows.length){
rowID--;
LetterChars = 0;
}
addLetter((TableRow)findViewById(rowID+4000+ rows.length-1));
TextView textView1 = (TextView)findViewById(i+5000);
textView1.setText(Character.toString(letters[i]));
LetterChars++;
}
}
private void fillWords(){
for(int i = 1; i < rows.length -1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
textView1.setText(words[i-1]);
}catch(Exception e){
textView1.setText("");
}
}
}
}
private void stringArrayToCharArray(){
char[] chars = new char[rows.length * rows.length];
int i = 0;
//selection of strings
for(int j = 0; j< rows.length; j++){
// selection of letters
for(int k = 0; k < rows.length; k++){
try{
chars[i] = rows[j].charAt(k);
}catch (Exception e){
Log.e("Error", "Error when adding chars");
}
i++;
}
}
letters = chars;
}
private void addLetter(TableRow row){
TextView textView1 = new TextView(this);
textView1.setId(letterID+5000);
textView1.setPadding(3,3,3,3);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
TableRow.LayoutParams textLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
textLayout.setMargins(10,0,0,10);
textView1.setTextAlignment(textView1.TEXT_ALIGNMENT_CENTER);
textView1.setGravity(Gravity.CENTER);
textView1.setTag(""+(letterID+1));
textView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
letterButonClick(v);
}
});
textView1.setOnDragListener(new View.OnDragListener() {
//draggin selection *To be implemented*
@Override
public boolean onDrag(View v, DragEvent event) {
return false;
}
});
textView1.setLayoutParams(textLayout);
row.addView(textView1);
letterID++;
}
private void addRows(){
for(int i= 0; i < rows.length;i++){
TableRow tableRow = new TableRow(this);
tableRow.setId(i+4000);
gridView.addView(tableRow);
}
}
private void checkWordFound(){
int foundID = 0;
for(String w: words){
if(selectedString.contains(w)){
//word that have been found
Log.i("Word Found", "Found: " + w);
//highlight words that have been found in the word list
for(int i = 1; i < rows.length-1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
if(textView1.getText().equals(w)){
//textview that contains the found words
textView1.setTextColor(Color.GREEN);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//add to found
wordsFound[foundID] =w;
columnFound[foundID] = columnsSelected[0];
rowFound[foundID] = rowsSelected[0];
directionFound[foundID] = directionSelected;
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
foundID++;
}
checkCompletion();
//no words are found
}
private void checkCompletion(){
if(Arrays.equals(words, wordsFound)){
new AlertDialog.Builder(this)
.setTitle("Word Search Complete")
.setMessage("Submit Score?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//submit score
submitResults();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
public void homeClicked(View v){
finish();
}
public void submitResults(){
}
@Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Solution Response", responseData);
//debug toasts
Toast.makeText(getApplication(),("Solution Submitted"), Toast.LENGTH_LONG).show();
finish();
}
}
error log
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-04 00:49:18.929 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone D/AndroidRuntime﹕ Shutting down VM
05-04 00:49:18.937 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sl.lloyd.steve.angrywordsearchthefinalone, PID: 6068
java.lang.RuntimeException: Unable to start activity ComponentInfo{sl.lloyd.steve.angrywordsearchthefinalone/sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.widget.AdapterView.addView(AdapterView.java:461)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.addRows(NewPuzzleActivity.java:320)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.onCreate(NewPuzzleActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Android - new algorithm on wifi channel scanning
I have two questions:
- I want to develop a new wireless channel scan algorithm on android devices. Android supports function this is
getScanResults()which inWifiManagerclass. Also how may I changegetScanResults()function. I want to use with passive channel scanning algorithm and unicast channal scanning algorithm - I want develop a android application sending Probe Request and listen probe response.
diffrence between Appcompact activity and actionbar activity
In Android What is the main difference between extending a class from AppCompatActivity and ActionBarActivity? How do these classes differ?
Android studio multithreaded downloader
I am trying to make a multuthreaded downloader which can download a given file by breaking it into 3 chunks and downloading in parallel. The issue is, when I run the code, it seems that Thread 2 doesnt start unless Thread 1 finishes and Thread 1 doesnt start until Thread 0 finishes. I want all the threads to run simultaneously, following is my code:
protected Void doInBackground(Void... params){
try{
if(ThreadName == "1")
{
Log.d("DownloaderSleeper", "putting thread 1 to sleep");
Thread.sleep(3000);
}
URL url = new URL(UrlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=" + StartingByte.toString() + "-" + EndingByte.toString());
connection.connect();
//File f = new File(TargetFileName);
Log.d("DownloaderThreadClass", F.toString() + TargetFileName);
RandomAccessFile file = new RandomAccessFile(F, "rw");
file.seek(StartingByte);
InputStream stream = connection.getInputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int nRead = 0;
int start = 0;
int i = 0;
while ((nRead = stream.read(buffer, start, bufferSize)) > 0) {
file.write(buffer, 0, nRead);
//start += bufferSize + 1;
Log.i("DownloaderThreadClass:" + ThreadName + ": ", "Chunk: " + i + "copied" );
i += 1;
}
file.close();
stream.close();
connection.disconnect();
}catch(Exception e){
Log.e("DownloaderThreadClass", "Some exception: " + e.getMessage());
}
return null;
}
The above code is being called like this:
protected Void doInBackground(Void... params) {
int chunkSize = 0;
int[] startByte = new int[3];
int[] endByte = new int[3];
try{
int fileSize = this.getFileSize();
if(fileSize > 0 && fileSize <= 1024 * 1024){
new DownloaderThreadClass("1", f, "http://ift.tt/1FPNdqb").execute();
}else if(fileSize > 1024 * 1024){
chunkSize = Math.round(fileSize / 3);
startByte[0] = 0;
endByte[0] = chunkSize - 1;
startByte[1] = chunkSize;
endByte[1] = chunkSize + chunkSize - 1;
startByte[2] = chunkSize + chunkSize;
endByte[2] = fileSize;
for (int i = 0; i < 3; i++){
new DownloaderThreadClass(Integer.toString(i), f, "http://ift.tt/1FPNdqb", startByte[i], endByte[i]).execute();
}
}
}catch(IOException e){
Log.e("DownloaderClass", "Exception getting file size: " + e.getMessage());
}
return null;
}
As you will see, I have two different classes, both extending AsynTask, and the flow is like this: Activity calls the first class on a click button and the first class class the second class in a loop of 3 iterations.
Sample URL: http://ift.tt/1FPNdqb
Android bug in Slide Activity transition
So in trying to use the Slide Activity transition but with a different gravity, the app crashes on using Gravity.START, using this:
getwindow().setExitTransition(new Slide(Gravity.START));
and I get this error:
IllegalArgumentException: Invalid slide direction
But yet if you look in the source code, that specific constructor above calls setSlideEdge() in which case that method goes through a switch statement to set the Gravity you specified earlier:
switch (slideEdge) { case Gravity.LEFT: mSlideCalculator = sCalculateLeft; break; case Gravity.TOP: mSlideCalculator = sCalculateTop; break; case Gravity.RIGHT: mSlideCalculator = sCalculateRight; break; case Gravity.BOTTOM: mSlideCalculator = sCalculateBottom; break; case Gravity.START: mSlideCalculator = sCalculateStart; break; case Gravity.END: mSlideCalculator = sCalculateEnd; break; default: throw new IllegalArgumentException("Invalid slide direction"); }
Gravity.LEFT works just fine, but because I want RTL support, it only makes sense to instead use Gravity.START. I'm confused as to why the default case is executed in this switch statement, and the only explanation for it is it's a bug.
I'd report it to Google but they don't have public ways of reporting API bugs like this, and in this case the bug isn't exactly obvious to fix. So, PSA to anyone that wants to use the Slide animation with a Gravity of START.
decode json object sent form android app to php server
I am sending json object from android as such:
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("key", String.valueOf(args[0]));
String postData=json.toString();
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(postData,"UTF-8"));
Log.i("NOTIFICATION", "Data Sent");
printout.flush ();
printout.close ();
When it is sent to the server it looks like the following code snippet. ???%7B%22key%22%3A%22value%22%7D I should add the first ??? are in a diamond each. When I decode the whole json object I get null. In the php server I have
$somevar=json_decode(json, true);
which returns null. Can someone point me on how to retrieve the json value? Thanks so much:)
Ionic background doesn't display in app
According to the Ionic forum (http://ift.tt/1GPuMhq) the backgroun image should display if you put it on the ion-content from the css file, like I'm doing:
.scroll-content {
background:url(/img/splash2.jpg);
background-size: cover;
background-repeat: no-repeat;
}
but it displays in every page in ionic serve but in none if you run the app on a device.
Any ideas?
Retrofit not parsing JSONObject
A successful login returns the following JSONObject from a server:
{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}
I want to put the response_data info into my User object. I used to do something like this:
String getResponse = jsonObject.getString("response_data");
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
//All the data in the `response_data` is initialized in `User`
User user = gson.fromJson(getResponse, User.class);
Now I tried doing the same in retrofit:
Initializing RestAdapter + Interface:
public class ApiClient {
private static RetrofitService sRetrofitService;
public static RetrofitService getRetrofitApiClient() {
if (sRetrofitService == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint("http://xxx.xxx.xxx.xxx/")
.build();
sRetrofitService = restAdapter.create(RetrofitService.class);
}
return sRetrofitService;
}
public interface RetrofitService {
@FormUrlEncoded
@POST("/login")
public void login(@Field("email_id") String emailId, @Field ("password") String password,
Callback <User> callback);
}
}
MainActivity:
ApiClient.getRetrofitApiClient().login(email.getText().toString(), password.getText().toString(),
new Callback<User>() {
@Override
public void success(User user, Response response) {
User user1 = user; //null
Toast.makeText(this, "user is: "+user1.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(this, "Failed Login", Toast.LENGTH_SHORT).show();
}
});
User:
public class User {
private String userId;
private String emailId;
private String code;
public User() {
}
... getters
... setters
}
The Retrofit code in MainActivity works and I get this response in my log:
{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}
However it doesn't parse the response_data into my User object.
How do I fix this?
Google Play Services: Can't solve the SIGN_IN_REQUIRED error
Before I back-pedalled into using the clean template activity, I had manually created an app that uses the GoogleAPIClient, which resulted in the app working (probably) on my device, but not on any other.
From creating the template Google Play activity, I only changed the manifest to include the app_id that I have registered with my Google Play Service account. When launching the app it shows a brief "Logging in" popup from Google Play, then continually tries to reconnect. Have tried with different devices on different computers. Have tried with both the owner's and assigned tester accounts. Same result.
I can't use any invite or room creating services.
Here is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.example.kai.twincrawler" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".TwinCrawlerActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="@string/app_id"/>
<meta-data android:name="com.google.android.gms.appstate.APP_ID"
android:value="@string/app_id"/>
</application>
</manifest>
Thanks for any help you can provide.
SoundCloud intents limited
Firstly, I was directed by my email to the developers to come here with my issue.
Hi, Simple Last.fm Scrobbler plans on having basic SoundCloud support in the newest version, but we have a problem with SoundCloud only releasing track strings of about 40 characters in length. Hence the information sent to last.fm or libre.fm is incomplete.
com.android.music.metadatachanged is the action being monitored.
The alternative My Cloud Player gives the full length track strings.
I was hoping to get feedback from SoundCloud Mobile developers about what is causing the track length shortages and if it will ever be fixed.
Run android application
when I run a program with android studio with emulator Nexus_5_API__21_x86 run and don't see environment android in emulator,my emulator stop in android logo in booting please help me
Any way to change background color of custom shape on click
I have a custom shape for my ListView background. But now it will not change color on click. Is there any way of doing this? Here is my xml for the ListView:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textSize="25sp"
android:textColor="#ff8d8d8d"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_alignParentLeft="true"
android:textColor="#ff8d8d8d"
android:textSize="25sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView1"
android:layout_alignParentRight="true"
android:textColor="#ff8d8d8d"
android:textSize="25sp" />
Here is the CustomShape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://ift.tt/nIICcg"
android:shape="rectangle">
<gradient android:startColor="#ffffff"
android:endColor="#ffd6d4d6"
android:angle="270"
/>
<corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp" android:topRightRadius="10dp"/>
Send Android Parse Push Notification to segment
I am trying to send push notifications to segment users in Android. Below is the code, it worked for few trials but now the same code send the push to everyone instead of the intended receiver (at the least that is what is shown on the dashboard). Anything I am doing wrong here?
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereEqualTo("user", ParseObject.createWithoutData("_User", mObject.get(position)));//receiver
ParsePush push = new ParsePush();
push.setQuery(pushQuery);
push.setMessage(alias +" followed you");
push.sendInBackground();
mObject.get(position) is where I get the objectId of the receiver in the installation class from and 'user' is a pointer to the _User class. Thanks
android studio is not builiding project for samsung 4.2.2
I have originally created my large project using Eclipse after android studio stable version came i migrated AS(Android studio).Currently Android studio is building for android 5.1 Nexus Tab 10 as well as 7 .but getting error after running on only samsung android 4.2.2.
appcompat-v7 v21.0.0 causing crash on Samsung devices with Android v4.2.2
i have tried above solution but problem is i don't have default proguard file as i have migrated from AS TO Eclipse .AS didn't generete proguard file.
then i did some research and created an app in eclipse and imported into Android Studio and it worked without using proguard .so my question what is happing AS is having problem or Samsung 4.2.2 with AppCompact. i got following error for samsung 4.2.2.plz guide me .thanks in advance
java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$layout at android.support.v7.app.ActionBarActivityDelegateBase.ensureSubDecor(ActionBarActivityDelegateBase.java:297) at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:225) at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102) at com.generaldevelopers.smartserve.activities.MainActicity.onCreate(MainActicity.java:41) at android.app.Activity.performCreate(Activity.java:5326) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309) at android.app.ActivityThread.access$700(ActivityThread.java:157) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5319) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method)
Android - Review video captured by custom camera before saving it
I can't find any information for this anywhere: I have created an Android custom camera in order to capture short videos. Instead of saving it directly on my mobile phone gallery, I would like first to review the video that I just capured, by watching it right after the recording, and with 2 buttons "Delete" and "OK".
Anyone knows how to do it? Do I have to create a new activity and using an intent?
Here is the current code which save the captured video on my mobile:
/** Saving Media Files */
/* Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("The app", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
Thank you so much for your help.
ActionBar tabs set as Target in showcaseview
I use deprecated Actionbar tabs and I want to set target of my ShowCaseView one of the tabs of my Actionbar does any body knows how can I achieve this ?
Fatal spin-on-suspend
I am getting this error after around 45 minutes of my service running, and then it crashes. I see this group of lines in the logcat when it does crash:
Thread pingo = new Thread(new Runnable()
{
public void run()
{
while (true)
{
if(socket2 != null)//Line 481
{
try {
ping = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket2.getOutputStream())), true);//Line 484
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ping.write("0000:PING" + "\r\n");
ping.flush();
// delay 5 seconds
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
break;
}
}
}
}
What this is supposed to do is ping the server every 5 seconds to ensure that the connection is kept alive. Is this the wrong way of doing this? Like I said it takes about 45 minutes or so for the crash to occur..
this is a snippet of the Logcat:
"Thread-20710" prio=5 tid=25 RUNNABLE
05-06 12:03:04.316: I/dalvikvm(21577): | group="main" sCount=0 dsCount=0 obj=0x42feb488 self=0x7290da00
05-06 12:03:04.316: I/dalvikvm(21577): | sysTid=28077 nice=0 sched=0/0 cgrp=apps/bg_non_interactive handle=2098243840
05-06 12:03:04.316: I/dalvikvm(21577): | state=R schedstat=( 0 0 0 ) utm=1 stm=2 core=3
05-06 12:03:04.316: I/dalvikvm(21577): at java.nio.ByteBuffer.allocate(ByteBuffer.java:~56)
05-06 12:03:04.316: I/dalvikvm(21577): at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:44)
05-06 12:03:04.316: I/dalvikvm(21577): at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:55)
05-06 12:03:04.316: I/dalvikvm(21577): at com.vli.emsa_mdt.SocketServiceController$2.run(SocketServiceController.java:484)
05-06 12:03:04.316: I/dalvikvm(21577): at java.lang.Thread.run(Thread.java:841)
05-06 12:03:04.316: I/dalvikvm(21577): "Thread-20707" prio=5 tid=23 RUNNABLE JIT
05-06 12:03:04.316: I/dalvikvm(21577): | group="main" sCount=1 dsCount=0 obj=0x439c8498 self=0x7d1328a8
05-06 12:03:04.316: I/dalvikvm(21577): | sysTid=27272 nice=0 sched=0/0 cgrp=apps handle=2098245016
05-06 12:03:04.326: I/dalvikvm(21577): | state=R schedstat=( 0 0 0 ) utm=20455 stm=7 core=2
05-06 12:03:04.326: I/dalvikvm(21577): at com.vli.emsa_mdt.SocketServiceController$2.run(SocketServiceController.java:~481)
05-06 12:03:04.326: I/dalvikvm(21577): at java.lang.Thread.run(Thread.java:841)
05-06 12:03:05.077: W/dalvikvm(21577): threadid=25: spin on suspend #3 threadid=23 (pcf=2)
05-06 12:03:05.077: I/dalvikvm(21577): "Thread-20710" prio=5 tid=25 RUNNABLE
T
Javassist - CannotCompileException: constructor/method declaration not found
I've got the following class which i want to use in my generated code with Javassist.
public class SomeClass {
private String someString;
private Object someValue;
public SomeClass() {}
public SomeClass(String someString, Object someValue) {
this.someString = someString;
this.someValue = someValue;
}
public void setSomeValue(Object someValue) {
this.someValue = someValue;
}
In Javassist i analyse some classes and their fields and then try to instatiate my SomeClass-class. But i get the following error for each field which has another type then java.lang.Object.
javassist.CannotCompileException: [source error] setSomeValue(int) not found in com.test.SomeClass
and
javassist.CannotCompileException: [source error] setSomeValue(double) not found in com.test.SomeClass
and so on. The same happens when i try to use the constructor.
Why this doesn't work?
By the way, Javassist is used in conjunction with Android.
Any good example for working with UNKNOWN CA signed certificate(like pkcs12) in android
I am working on android application, which requires to communicate with server over ssl. Any good example to work with pkcs12 certificates in android using HttpsUrlConnection
Cant validate Login on Android app using an api request
i'm trying to create a login form that connects to an API and authorizes the username and password but whenever i press the onClickListener which is my LogIn button the app crashes. The username and password is hardcoded in my code.
Code:
public class LoginActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_login);
Button buttonLogin = (Button)findViewById(id.buttonLogin);
EditText uEmail = (EditText) findViewById(id.emailField);
EditText uPassword = (EditText) findViewById(id.passwordField);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
Request request = new Request.Builder().url("MyUrlThatIdontWannaShow").build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Context context = getApplicationContext();
CharSequence text = "Error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
@Override
public void onResponse(Response response) throws IOException {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
});
}
}
XML:
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".LoginActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logga in"
android:id="@+id/buttonLogin"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/emailField"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/passwordField"
android:layout_below="@+id/emailField"
android:layout_alignLeft="@+id/emailField"
android:layout_alignStart="@+id/emailField"
android:text="lösenord"/>
The error i get:
C:\Users\Dan\AndroidStudioProjects\LogsterAndroid\app\src\main\java\com\example\danial\logsterandroid\LoginActivity.java:23: error: cannot find symbol
uEmail = (EditText)findViewById(R.id.emailField);
^
symbol: variable uEmail location: class LoginActivity C:\Users\Dan\AndroidStudioProjects\LogsterAndroid\app\src\main\java\com\example\danial\logsterandroid\LoginActivity.java:24: error: cannot find symbol uPassword = (EditText)findViewById(R.id.passwordField); ^ symbol: variable uPassword location: class LoginActivity 2 errors
FAILED
FAILURE: Build failed with an exception.
-
What went wrong: Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.
-
Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Thanks in advance!
How can I test setResult() in an Android Espresso test?
Is there any good way to test the result code and data in an Android Espresso test? I am using Espresso 2.0.
Suppose I have an Activity called BarActivity.class, which upon performing some action, calls setResult(int resultCode, Intent data) with the appropriate payload.
I'd like to write a test case to verify the resultCode and data. However, because setResult() is a final method, I can't override it.
Some options I thought about were:
- Define a new method like
setActivityResult()and just use that so it can be intercepted, etc... - Write a test-only TestActivity that will call
startActivityForResult()onBarActivityand check the result inTestActivity.onActivityResult()
Trying to think what's lesser of the two evils, or if there's any other suggestions on how to test for this. Any suggestions? Thanks!
IBM MobileFirst - Can't subscribe, notification token is not updated on the server
I'm unable to subscribe my application, built using IBM MobileFirst Platform, for push notification. I'm getting the error message
WLPush.isAbleToSubscribe in WLPush.java:414 :: Can't subscribe, notification token is not updated on the server
LogCat
05-06 10:20:44.767 20941-20941/com.vdot.pushdemo D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-06 10:20:44.887 20941-21582/com.vdot.pushdemo D/WLClient﹕ WLClient.createInstance in WLClient.java:213 :: WLClient has already been created.
05-06 10:20:44.917 20941-21582/com.vdot.pushdemo D/GCMClientFactory﹕ GCMClientFactory.getInstance in GCMClientFactory.java:25 :: Using GCMAPIClient
05-06 10:20:44.937 20941-21582/com.vdot.pushdemo W/com.worklight.wlclient.api.WLPush﹕ WLPush.unregisterReceivers in WLPush.java:792 :: unregisterReceivers:Receiver not registered: com.worklight.wlclient.api.WLPush$3@43a3d598
05-06 10:20:44.967 20941-21582/com.vdot.pushdemo D/wl.request﹕ WLRequestSender.run in WLRequestSender.java:40 :: Sending request http://ift.tt/1AF7o3Y
05-06 10:20:45.267 20941-21681/com.vdot.pushdemo I/System.out﹕ pool-3-thread-6 calls detatch()
05-06 10:20:45.307 20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateToken in WLPush.java:521 :: Registering at the GCM server.
05-06 10:20:45.327 20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.clearSubscribedEventSources in WLPush.java:596 :: Clearing notification subscriptions.
05-06 10:20:45.337 20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateSubscribedEventSources in WLPush.java:614 :: Updating notification subscriptions.
05-06 10:20:45.347 20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.clearSubscribedTags in WLPush.java:607 :: Clearing tag notification subscriptions.
05-06 10:20:45.357 20941-21681/com.vdot.pushdemo D/com.demo.push﹕ Mode Connect Success
05-06 10:20:45.367 20941-21582/com.vdot.pushdemo D/com.worklight.wlclient.api.WLPush﹕ WLPush.updateSubscribedTags in WLPush.java:635 :: Updating tag notification subscriptions.
05-06 10:20:45.497 20941-21582/com.vdot.pushdemo D/GCMAPIClient﹕ GCMAPIClient$1.doInBackground in GCMAPIClient.java:45 :: Successfully registered with GCM using Google Play Services. Returned deviceToken:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-06 10:20:45.507 20941-21682/com.vdot.pushdemo D/com.demo.push﹕ onReadyToSubscribe
05-06 10:20:50.697 20941-20941/com.vdot.pushdemo D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-06 10:20:50.827 20941-21582/com.vdot.pushdemo D/WLClient﹕ WLClient.createInstance in WLClient.java:213 :: WLClient has already been created.
05-06 10:20:50.847 20941-21582/com.vdot.pushdemo D/GCMClientFactory﹕ GCMClientFactory.getInstance in GCMClientFactory.java:25 :: Using GCMAPIClient
05-06 10:20:50.857 20941-21582/com.vdot.pushdemo W/com.worklight.wlclient.api.WLPush﹕ WLPush.unregisterReceivers in WLPush.java:792 :: unregisterReceivers:Receiver not registered: com.worklight.wlclient.api.WLPush$3@43a800e0
05-06 10:20:50.877 20941-21582/com.vdot.pushdemo E/com.worklight.wlclient.api.WLPush﹕ WLPush.isAbleToSubscribe in WLPush.java:414 :: Can't subscribe, notification token is not updated on the server
Main Activity
package com.vdot.pushdemo;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.worklight.wlclient.WLRequestListener;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLEventSourceListener;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLOnReadyToSubscribeListener;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLPush;
import com.worklight.wlclient.api.WLPushOptions;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;
public class MainActivity extends Activity {
Button Push;
Button Sub;
Button UnSub;
Button Test;
Button Logout;
WLClient client;
WLPush push;
final String realm = "SampleAppRealm";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Push =(Button) findViewById(R.id.button0);
Sub =(Button) findViewById(R.id.button1);
UnSub =(Button) findViewById(R.id.button2);
Test =(Button) findViewById(R.id.button3);
Logout = (Button) findViewById(R.id.button4);
setupUIEvents();
}
void setupUIEvents(){
Push.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
client = WLClient.createInstance(MainActivity.this);
push = client.getPush();
PushListener listener = new PushListener(PushListener.MODE_CONNECT, MainActivity.this);
push.setOnReadyToSubscribeListener(listener);
client.registerChallengeHandler(new LoginChallengeHandler(realm, "IBM User", MainActivity.this));
client.connect(listener);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client = WLClient.createInstance(MainActivity.this);
client.getPush().subscribe("myAndroid",new WLPushOptions(), new PushListener(PushListener.MODE_SUBSCRIBE,MainActivity.this));
}
});
UnSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client = WLClient.createInstance(MainActivity.this);
PushListener listener = new PushListener(PushListener.MODE_CONNECT, MainActivity.this);
client.registerChallengeHandler(new LoginChallengeHandler(realm, "IBM User", MainActivity.this));
client.connect(listener);
int i = 0;
while (i < 10000)
{
i++;
}
String adapterName = "PushAdapter";
String procedureName = "getSecretData";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
Object[] parameters = new Object[]{};
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
client.getInstance().invokeProcedure(invocationData, listener, options);
}
});
Logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client = WLClient.createInstance(MainActivity.this);
client.logout(realm,new MyListener());
}
});
}
public class MyListener implements WLRequestListener{
@Override
public void onSuccess(WLResponse wlResponse) {
Log.d("com.demo.push", "Log out success");
}
@Override
public void onFailure(WLFailResponse wlFailResponse) {
Log.d("com.demo.push", "Log out failed");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
if (push != null)
push.setForeground(false);
}
@Override
protected void onResume() {
super.onResume();
int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(code == ConnectionResult.SERVICE_MISSING || code == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED || code == ConnectionResult.SERVICE_DISABLED) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(code, this, 1);
dialog.show();
}
if (push != null)
push.setForeground(true);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (push != null)
push.unregisterReceivers();
}
}
Login Challenge Handler
package com.vdot.pushdemo;
import android.content.Context;
import android.content.Intent;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.challengehandler.ChallengeHandler;
public class LoginChallengeHandler extends ChallengeHandler {
private String userName;
private Context currentContext;
public LoginChallengeHandler(String realm, String user, Context ctx) {
super(realm);
userName = user;
currentContext = ctx;
}
@Override
public boolean isCustomResponse(WLResponse wlResponse) {
try {
if(wlResponse!= null &&
wlResponse.getResponseJSON()!=null &&
wlResponse.getResponseJSON().isNull("authRequired") != true &&
wlResponse.getResponseJSON().getBoolean("authRequired") == true){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public void handleChallenge(WLResponse wlResponse) {
submitLogin(userName,"dummyPassword");
}
@Override
public void onSuccess(WLResponse wlResponse) {
// activity.Loader("Authenticate","Authentcating via VDOT secure server",false);
if(isCustomResponse(wlResponse))
{
handleChallenge(wlResponse);
}
else
{
submitSuccess(wlResponse);
}
}
@Override
public void onFailure(WLFailResponse wlFailResponse) {
submitFailure(wlFailResponse);
}
public void submitLogin(String userName, String password){
Object[] parameters = new Object[]{userName, password};
WLProcedureInvocationData invocationData = new WLProcedureInvocationData("PushAdapter", "submitAuthentication");
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
submitAdapterAuthentication(invocationData, options);
}
}
Push Listener
package com.vdot.pushdemo;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLEventSourceListener;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLOnReadyToSubscribeListener;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;
public class PushListener implements WLOnReadyToSubscribeListener,WLResponseListener,WLEventSourceListener {
public static final int MODE_CONNECT = 0;
public static final int MODE_SUBSCRIBE = 1;
public static final int MODE_UNSUBSCRIBE =2;
private int mode ;
private Context currentContext;
public PushListener(int mode, Context ctx){
this.mode = mode;
currentContext = ctx;
}
@Override
public void onReadyToSubscribe() {
WLClient.getInstance().getPush().registerEventSourceCallback("myAndroid", "PushAdapter","PushEventSource", this );
Log.d("com.demo.push", "onReadyToSubscribe");
}
@Override
public void onReceive(String arg0, String arg1) {
}
@Override
public void onSuccess(WLResponse wlResponse) {
switch (mode){
case MODE_CONNECT:
// connect =true ;
Log.d("com.demo.push", "Mode Connect Success");
break;
case MODE_SUBSCRIBE:
Log.d("com.demo.push", "Mode Subscribe Success ");
break;
case MODE_UNSUBSCRIBE:
// unsubscribe = true;
break;
}
}
@Override
public void onFailure(WLFailResponse wlFailResponse) {
switch (mode){
case MODE_CONNECT:
Log.d("com.demo.push", "Mode Connect Fail");
break;
case MODE_SUBSCRIBE:
Log.d("com.demo.push", "Mode Subscribe Fail");
break;
case MODE_UNSUBSCRIBE:
// unsubscribe = false;
break;
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.vdot.pushdemo" >
<permission android:name="com.vdot.pushdemo.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="com.vdot.pushdemo.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.parse.push.notification_icon"
android:resource="@drawable/push" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.vdot.pushdemo.MainActivity.NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service android:name="com.worklight.wlclient.push.GCMIntentService" />
<receiver android:name="com.worklight.wlclient.push.WLBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.vdot.pushdemo" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.vdot.pushdemo" />
</intent-filter>
</receiver>
</application>
</manifest>
WLCLient.Properties
wlServerProtocol = http
wlServerHost = NG00164378
wlServerPort = 10080
wlServerContext = /MFPushDemo/
wlAppId = AndroidPushDemo
wlAppVersion = 1.0
wlEnvironment = Androidnative
wlUid = wY/mbnwKTDDYQUvuQCdSgg==
wlPlatformVersion = 7.0.0.0
#languagePreferences = Add locales in order of preference (e.g. en, fr, fr-CA)
#For Push Notifications,uncomment below line and assign value to it
GcmSenderId = 64XXXXXXXXXX
Android serialization issue
I am trying to write object data to a file (how it's done in a standard java program) in an android program and am running in to some issues. Here's the code:
public static final String storeDir = "Adata";
public static final String storeFile = "albums";
public static void write(ArrayList<Album> albums) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(storeDir + File.separator + storeFile));
oos.writeObject(albums);
}
public static ArrayList<Album> read() throws IOException, ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream( new FileInputStream(storeDir + File.separator + storeFile));
return (ArrayList<Album>)ois.readObject();
}
At startup the app crashes and says, "java.io.FileNotFoundException: Adata/albums (No such file or directory)
The folder Adata folder is in the project folder at the same point as the src. Any help is appreciated. Thanks.
Justify android TextView library
I wanna to justify text in android.but i don't want to use web View. I find Text Justify Android library on following link. but i can't use it. please help me to use this library in android studio thanks a lot...
Android gradle modules with the same name
I am working on an Android project that uses the following dependency:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.17</version>
</dependency>
However this dependency has 2 definitions of the module javax/inject as shown here in the gradle dependency tree:
+--- org.glassfish.jersey.core:jersey-client:2.17
| +--- org.glassfish.jersey.core:jersey-common:2.17
| | +--- org.glassfish.hk2:hk2-api:2.4.0-b10
| | | +--- javax.inject:javax.inject:1
| | +--- org.glassfish.hk2.external:javax.inject:2.4.0-b10
When attempting to run the Android application I get the error:
com.android.dex.DexException: Multiple dex files define L/javax/inject/Inject
I have tried excluding either of these modules but that does not work because the dependency relies on both of them to make method calls.
Are there any other solutions to resolve this conflict?
Hidden tab headers on Tabbed Activity
As a beginner of Android Studio, I have a main activity with an image button that starts Tabbed activity. I've added a new activity using
Right Click > New > Activity > Tabbed Activity
It creates activity_tabbed.xml and fragment_tabbed.xml
fragmented_tabbed.xml contgains :
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.webraya.t0.t0.Tabbed$PlaceholderFragment">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/a"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
and activity_tabbed.xml contains :
<android.support.v4.view.ViewPager xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:id="@+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.webraya.t0.t0.Tabbed" />
When I run the app and touch the imagebutton and the Tabbed activity starts, the result is :
when I swipe from right to left, it seems I have 3 tabs with the same picture. I don't know why there is no tab header, and why there are three tabs with the same content, how to create headers and change tabs contents? My theme is Theme.AppCombat.Light.DarkActionBar
Any help would be appreciated.
How to save audio sample data from .wav file to text file and vice versa, for resampling in android.
I have recorded and saved audio to a .wav file in android application. I want to read the sample data from .wav file (which I have done already), save that to a text file and vice versa, for resampling.
Android invalid resource directory name:appcompat_v7\bin\res crunch
My app add the v7 lib under the libraries dependency. When I run the build script(under Eclipse), I got the following error:
[mergemanifest] Manifest merger disabled. Using project manifest only.
[echo] Handling aidl files...
[aidl] No AIDL files to compile.
[echo] ----------
[echo] Handling RenderScript files...
[echo] ----------
[echo] Handling Resources...
[aapt] Generating resource IDs...
[aapt] invalid resource directory name: D:\Workspace\appcompat_v7\bin\res crunch
I tried everything, but can't figure out how to solve it. Any help? This happens with all libraries I added, so I'm forced to use the .jar instead but v7 appears has no jar.