dimanche 19 avril 2015

Data not being stored when using Spring JPA with android

I am developing an app which would talk to the server which is developed using spring. I got to a point where we i was getting data from the google api and wanted to pass it to the spring server. But when i do pass it, the server accepts it but the data is not being stored in the mysql database.


Here is the code I am using:


This is the main spring application + controller:



@EnableJpaRepositories(basePackageClasses = StudentRepository.class)

@SpringBootApplication
public class Demo3Application {

public static void main(String[] args) {
SpringApplication.run(Demo3Application.class, args);
}
}

@RestController
class StudentController
{
@Autowired
public StudentRepository students;

@RequestMapping(value = "/getstudent", method = RequestMethod.GET)
public @ResponseBody List<Student> fetchStudents()
{

if(students.count() == 0)
{
Vector<VideoList> no_video = new Vector<VideoList>();
VideoList no_v = new VideoList("No Videos found", null, null, null);
no_video.add(no_v);
return no_video;
return null;
}

return null;
}

@RequestMapping(value = "/poststudent" , method = RequestMethod.POST)
public @ResponseBody String putStudents(@RequestBody Student v )
{

students.save(v);

return "Student Successfully Added";


}

@RequestMapping(value = "/searchstudent/{str}" , method = RequestMethod.GET)
public @ResponseBody String searchStudent(
@PathVariable("str") String searchQuery
)
{
if(students.existsByEmail(searchQuery)){
List<Student> sList = students.findEmail(searchQuery,new PageRequest(0, 1));
Student s = sList.get(0);
String str = "";
Vector<CourseList> c = s.getCourses();
Iterator<CourseList> it = c.iterator();
while(it.hasNext()){
str.concat(it.next().toString());
str.concat("\n");
}
return str;
}

return null ;

}

@RequestMapping(value = "/addcourse" , method = RequestMethod.POST)
public @ResponseBody String postCourse(@RequestParam String email, @RequestParam String course){
List<Student> sList = students.findEmail(email,new PageRequest(0, 1));
Student s = sList.get(0);
CourseList c = new CourseList();
c.setName(course);
s.addCourse(c);
students.save(s);
return null;
}

}


This is the Student class:



@Entity
@Table(name = "table1")
public class Student {

private String name;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String email;

private Vector<CourseList> courses = new Vector<CourseList>();//CourseList is just a class to store data about various courses.
public Student(){}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public Vector<CourseList> getCourses(){
return courses;
}
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public void setCourses(Vector<CourseList> courses){
this.courses = courses;
}
public void addCourse(CourseList c){
courses.add(c);
}
}


This is my repository:



@Repository
@Transactional
public interface StudentRepository extends CrudRepository<Student,String>{

@Query("SELECT s FROM Student s WHERE email = ?1")
public List<Student> findEmail(String searchQuery, Pageable pageable);

@Query("SELECT CASE WHEN COUNT(s) > 0 THEN 'true' ELSE 'false' END FROM Student s WHERE s.email = ?1")
public boolean existsByEmail(String searchQuery);


}


This is my application.properties file:



spring.datasource.url: jdbc:mysql://localhost/mydb
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.username: root
spring.datasource.password:root

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


And finally here is the android code to test the above:



public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {

private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";

// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;

private boolean mSignInClicked;

private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;
private Button btnSignOut;
private ImageView imgProfilePic;
private TextView txtName, txtEmail, course;
private LinearLayout llProfileLayout;
private Button SC;

private String personName;
private String personPhotoUrl;
private String personGooglePlusProfile;
private String email;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
course = (TextView) findViewById(R.id.txtCourses);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
SC=(Button)findViewById(R.id.Scourse);

// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
SC.setOnClickListener(this);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}

protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}

if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;

if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}

}

@Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}

mIntentInProgress = false;

if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

// Get user's information
getProfileInformation();


// Update the UI after signin
updateUI(true);

}

/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
getCourses();
SC.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
course.setText(" ");
SC.setVisibility(View.GONE);
}
}

private void getCourses(){
new StudentSearch().execute();
}



private class StudentSearch extends AsyncTask<String, Void, String >
{

String content = "";
@Override
protected String doInBackground(String... urls) {

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://ift.tt/1Don8s7"+email);

StringBuffer studentString = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpget);
InputStream responseString = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(responseString));
String res = "";
if ((res = reader.readLine()) == null) {
studentString.append("");
HttpPost httpPost = new HttpPost("http://ift.tt/1yH0v6s");

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", personName);
jsonObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}

try {
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}

} else {
studentString.append(res);
studentString.append("\n");
while ((res = reader.readLine()) != null) {
studentString.append(res);
studentString.append("\n");
}

}
}
catch(Exception e)
{
e.printStackTrace();
}

return studentString.toString();
}

@Override
protected void onPostExecute(String s) {
if (!s.isEmpty()){
course.setText("Courses Taken:\n"+s);}
else
course.setText("No Courses Taken!");

}
}

/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName = currentPerson.getDisplayName();
personPhotoUrl = currentPerson.getImage().getUrl();
personGooglePlusProfile = currentPerson.getUrl();
email = Plus.AccountApi.getAccountName(mGoogleApiClient);

Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);

txtName.setText(personName);
txtEmail.setText(email);

// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;

new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);

} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}

/**
* Button on click listener
* */
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.Scourse:
{
Intent intent=new Intent(MainActivity.this,SelectCourse.class);
startActivity(intent);
break;
}
}
}

/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}

/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}

/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

}


I am a total newbie when it comes to developing spring code and would really appreciate some help.


Get Android phone camera input and stream to Android-Wear

How can I stream camera input from Android phone and display it on an Android-Wear device?


Bitmap(Compress/Drawing Canvas/Save)

i have a big trouble.

So i'm using camera API to make some photo,after that i need to add some text+rect on image and save into phone memory (internal).

I found solution like this :

1) calling api camera

2) OnActivityResult calling methods, which i converting image to bitmap,adding some text + Rectangle via Paint/Canvas(on image) and after this manipulation,saving my finished image(drawn text+rectangle) via BitmapCompress.



The problem is that Compress function load full image size into RAM memory and if ill make a few photo's,app will crash with OutOfMemoryException. My was trying to make workaround like this(worst variant) :

1)using asynchrone Compress(await mechanism)

2)when Compress is done,calling Bitmap.Recycle()



But this solution doesnt helped me. Await Compress saving photo with delay 2-3 seconds and i need to save my photo immediately (like how it doing Camera Api's).


PS Sorry for my Perfect english skills.

PPS Also have bug with text appearance(always drawing vertically,but i need horizontally).


Android - Customizing Position of Toast Message

I have a toast message and the default setting is displaying it bottom-center on the screen. I am wondering how to position it TOP-center. Any ideas?


Thank you


My character associated to Image Target barely moves

I'm developing an android augmented reality game using unity 3d engine and vuforia extension where I need to move a character over a image target.


The problem is when I associate the character to the image target (as a child of image target) the movement is like the character is "glued" to the plane, it barely moves from his position, it moves very slowly.


I already tested without using augmented reality and the moving of the character is completly fine, so I dont know what am I doing wrong ...


Thanks in advance.


ListView OnClick with filling

I'm little lost filling a ListView from a List. I can fill it with one element, but I want to get three elements from the object, so when I touch each element the app go to the link it contain. In my actual code I just can show the title



protected void onPostExecute (Boolean result){

List <String> title = new ArrayList<String>();
List <String> link = new ArrayList<>();
List <String> date = new ArrayList<>();
for(int i=0;i<news.size();i++)
{
title.add(news.get(i).getTitle());
link.add(news.get(i).getLink());
date.add(news.get(i).getDate());
}
ArrayAdapter <String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,title);
result.setAdapter(adapter);
dialog.dismiss();
}


In the arraylist date and link, I save the correct data, but I just can use one of them. My intention is to put date below the title and when you touch each element, the browser opens with the link selected.


Thanks a lot.


EDIT: I've done the custom adapter, but it gives me an error.



class CustomAdapter extends ArrayAdapter<whatsnew> {

public CustomAdapter(Context context, whatsnew[] data) {
super(context, R.layout.listitem, data);
}

public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View item = inflater.inflate(R.layout.listitem, null); //This give me a warning

TextView lblTitle = (TextView)item.findViewById(R.id.lbltitle);
lblTitle.setText(data[position].getTitle());

TextView lbldate = (TextView)item.findViewById(R.id.lbldate);
lbldate.setText(data[position].getFecha());

return(item);

}

}
CustomAdapter adaptader = new CuestomAdapter(getActivity(), data);
result.setAdapter(adaptador);
dialog.dismiss();


My Logcat says:



Java NullPointerException: storage == null

Change value from resources (int / strings / styles / etc ) programmatically

I'm trying to change the value of a resource, but many post say you can not change, I think if you can, but do not know how yet.


In the Xml I have something like this:



<resources xmlns:android="http://ift.tt/nIICcg">
<integer name="textSize">11</integer>
</resources>


to obtain the value



int update_str = this.getResources().getInteger (R.integer.textSize);


but to change it?



???


I can get all the textviews and change the parameter individually, but if we have 1000 textviews on each page, I think it is a bit forced and drastic to the% cpu hardware.


How to end an activity and reset SharedPreferences.Editor value?

I am creating a quiz app with Android studio. I have an activity and pager adapter in it which contains 3 fragments(questions). When I answer all questions(the code I've written below checks only the first question just to not take up much space) and press the End button new activity opens up and shows the result. But sometimes the result is shown not correctly. I suspect that my SharedPreferences.Editor value is incorrect when I start the test activity, so I've tried to set it 0 once the activity is launched. Still the problem remained.


It might be that I am using wrong method in a fragment to send the results (onStop() in this case, but I've also tried onDetach, onDestroyView, onDestroy).


Also I've tried changing editor.apply() to editor.commit() , no difference whatsoever.


Question1.java



public class Question1 extends android.support.v4.app.Fragment {

private CheckBox cb1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStance) {
View v = inflater.inflate(R.layout.fragment_question1, null);
return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}


@Override
public void onStop() {
super.onStop();

cb1 = (CheckBox)getView().findViewById(R.id.checkBox1);

final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = app_preferences.edit();

if (cb1.isChecked()) {
editor.putInt("answer_value", 1);
} else {
editor.putInt("answer_value", 0);
}
editor.apply();
}

}


Test.java



public class testActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
defaultValue();
}

private void defaultValue() {
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = app_preferences.edit();

editor.putInt("answer_value", 0);
editor.apply();
}

public void goResult(View view){
Intent intent = new Intent(testActivity.this, Result.class);
startActivity(intent);
}


private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,Qestion1.class.getName()));
fragments.add(Fragment.instantiate(this,Qestion2.class.getName()));
fragments.add(Fragment.instantiate(this,Question3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);

Collections.shuffle(fragments, new Random(System.nanoTime()));

ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_greitas_testas, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;}
return super.onOptionsItemSelected(item);
}

}


Result.java



public class Result extends ActionBarActivity {

TextView win_lose;
int Ats1, Ats2, Ats3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_result);
calculateResult();
}


private void calculateResult() {
win_lose = (TextView)findViewById(R.id.textView9);

final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

int Ans1 = app_preferences.getInt("answer_value", 0);

if ( Ans1 == 1 ){
win_lose.setText("Win");
} else {
win_lose.setText("Lose");
}

}

public void onBackPressed(){
Intent intent = new Intent(Result.this, mainActivity.class);
startActivity(intent);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_result, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}


PagerAdapter.java



public class PagerAdapter extends FragmentPagerAdapter {

private List<Fragment> fragments;

public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}

@Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}

@Override
public int getCount() {
return this.fragments.size();
}

public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}

Shortcut for Overriding methods in Android Studio

I have recently migrated to Android Studio and I am pretty used to the Source -> Override/Implement feature in Eclipse.


Methods in Eclipse


I was wondering where I could find the same feature on Android Studio. I've tried "Alt-Insert"/Generate-Override methods but I don't find the OnPause() method to override in the list. How do I get the methods that I want to override in the list?


Getting No resource identifier found for attribute 'adSize' in package right after adding compile "com.google.android.gms:play-services:3.1.+"

I am getting



No resource identifier found for attribute 'adSize' in package



and



No resource identifier found for attribute 'adUnitId' in package



error since I updated build.gradle file.


build.gradle



apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
applicationId "com.example.admobdemo"
minSdkVersion 11
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile "com.google.android.gms:play-services:3.1.+"

compile project(path: ':backend', configuration: 'android-endpoints')
}


If I replace



compile "com.google.android.gms:play-services:3.1.+"


with



compile 'com.google.android.gms:play-services:7.0.0'


It work.But I am also implementing GCM Push notification in app. According to google docs I have to add google-play-service:3.1.+.


My_Activity.xml



<android.support.v4.widget.DrawerLayout xmlns:ads="http://ift.tt/GEGVYd"
xmlns:android="http://ift.tt/nIICcg"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- The main content view -->

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
xmlns:ads="http://ift.tt/GEGVYd"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="0dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

android:background="@color/dark_brown"
android:orientation="vertical"
tools:context=".GeneralInstructionsActivity" >

<WebView
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>

<Button
android:id="@+id/otherAppsBtn"
style="@style/ButtonStyle"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:padding="3dp"
android:layout_gravity="center"
android:layout_margin="3dp"
android:gravity="center"
android:onClick="showOtherApps"
android:text="@string/otherApps"
android:textSize="17sp"
android:typeface="serif" />

<!-- <com.google.android.gms.ads.AdView
android:id="@+id/about_adView"
android:background="@android:color/background_dark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adUnitId="@string/ad_unit_id"
ads:adSize="SMART_BANNER"
/>-->
<com.google.android.gms.ads.AdView
android:id="@+id/about_adView1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="@string/ad_unit_id" >
</com.google.android.gms.ads.AdView>

</LinearLayout>


<!-- The navigation drawer -->

<LinearLayout
android:id="@+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#f4f4f4"
android:orientation="vertical" >

<ExpandableListView
android:id="@+id/drawer_list1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/dark_brown"
android:cacheColorHint="#00000000"
android:divider="#666666"
android:dividerHeight="2dp"
android:groupIndicator="@android:color/transparent" />
</LinearLayout>


Any help will be appreciated!


Thanks.


Cannot add cordova-plugin-uid to Visual Studio 2013 project

When trying to add http://ift.tt/1HlOd4Y to visual studio via the config.xml designer, it "recognises" there is a plugin, but ends with blank fields for all the properties (version, plugin id, etc.), even if you wait for minutes (most others find all properties in seconds). If the then try and add it, it simply crashes VS and restarts. I have tried with plugins that do not support ALL platforms, with success, but not this one.


Has anyone had any luck adding this to VS or have any ideas. Since the project is cross platform, I would prefer to use the recommended way, even though this is android only, but am open to suggestions. Ultimately, I am only looking for IMEI.


RxJava Observable does'nt emmits item

I write client app for kaltura video platform, and now, I develop playlist building from video list. You can drag video from one list and drop to another. First of all, I want to get all videos(without filter) and put it to



List<KalturaVideo> sourceList;


variable. When you added video to



List<KalturaVideo> targetList;


I want to remove this item from sourceList. So, I have a class KalturaVideoRetriver, which has one public method:



public static Observable<KalturaVideo> getVideoList(Context context, String kalturaPlaylistId)


It return Observable, and I want to get KalturaVideo items from this observable. This is the code of KalturaVideoRetriver class:



public class KalturaVideoRetriver {

public static final String KALTURA_NEW_PLAYLIST_ID = "NEW_PLAYLIST";

public static Observable<KalturaVideo> getVideoList(Context context, String kalturaPlaylistId){
return Observable.create(new Observable.OnSubscribe<KalturaVideo>() {
@Override
public void call(Subscriber<? super KalturaVideo> subscriber) {
getKalturaPlaylistContentObservable(kalturaPlaylistId, context)
.flatMap(new Func1<String[], Observable<?>>() {
@Override
public Observable<?> call(String[] videoIdList) {
return getKalturaVideoListObservable(context, videoIdList);
}
});
}
});
}

private static Observable<KalturaVideo> getKalturaVideoListObservable(Context context, String[] kalturaVideoIdArray){
return Observable.create(new Observable.OnSubscribe<KalturaVideo>() {
@Override
public void call(Subscriber<? super KalturaVideo> subscriber) {
Cursor query;
List<KalturaVideo> result = new ArrayList<>();
if(kalturaVideoIdArray == null || kalturaVideoIdArray.length == 0) {
query = context.getContentResolver().query(KalturaVideoColumns.CONTENT_URI, null, null, null, null);
}else{
KalturaVideoSelection where = new KalturaVideoSelection();
where.kalturaIdLike(kalturaVideoIdArray);
query = context.getContentResolver().query(
KalturaVideoColumns.CONTENT_URI,
null,
where.sel(),
where.args(),
null);
if(!query.moveToFirst()){
subscriber.onCompleted();
}
KalturaVideoCursor cursor = new KalturaVideoCursor(query);
do{
KalturaVideo video = new KalturaVideo();
video.setId(cursor.getKalturaId());
video.setName(cursor.getName());
video.setDescription(cursor.getDescription());
video.setCategories(cursor.getCategories());
video.setCategoriesIds(cursor.getCategoriesIds());
video.setDownloadUrl(cursor.getDownloadUrl());
video.setThumbnailUrl(cursor.getThumbnailUrl());
video.setDataUrl(cursor.getDataUrl());
video.setDuration(cursor.getDuration());
subscriber.onNext(video);
}while (query.moveToNext());
subscriber.onCompleted();
}
}
});
}

private static Observable<String[]> getKalturaPlaylistContentObservable(String kalturaPlaylistId, Context context){
return Observable.create(new Observable.OnSubscribe<String[]>() {
@Override
public void call(Subscriber<? super String[]> subscriber) {
KalturaPlaylistContentSelection where = new KalturaPlaylistContentSelection();
where.playlistId(kalturaPlaylistId);
Cursor query = context.getContentResolver().query(
KalturaPlaylistContentColumns.CONTENT_URI,
null,
where.sel(),
where.args(),
null
);
if(!query.moveToFirst()){
subscriber.onNext(new String[]{});
subscriber.onCompleted();
}
KalturaPlaylistContentCursor cursor = new KalturaPlaylistContentCursor(query);
String[] result = new String[query.getCount()];
int index = 0;
do{
result[index] = cursor.getKalturaVideoId();
index++;
}while (query.moveToNext());
subscriber.onNext(result);
subscriber.onCompleted();
}
});

}

}


getKalturaPlaylistContentObservable - gets me array of KalturaVideo id's by kalturaPlaylistId. If kalturaPlaylistId is KALTURA_NEW_PLAYLIST_ID, then it gets me empty array, which means, that I want to get all videos in my SQLite db.


getKalturaVideoListObservable - gets me KalturaVideo items by array of video id from getKalturaPlaylistContentObservable. If array is empty, then it gets me all videos, which I have.


Also, I have an Activity: BuildPlaylistStep2Activity. In this activity I want to display videos if sourceList, and targetList. Here is the code of activity:



public class BuildPlaylistStep2Activity extends BaseActivity implements View.OnTouchListener {

public ViewHolder viewHolder;
private View selected_item = null;
Boolean touchFlag = false;
boolean dropFlag = false;
LayoutParams viewParams;

List<KalturaVideo> sourceList;
List<KalturaVideo> targetList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_playlist_step2);
viewHolder = new ViewHolder();
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getSourceListObservalbe(KalturaVideoRetriver.KALTURA_NEW_PLAYLIST_ID)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(kalturaVideo -> {
sourceList.add(kalturaVideo);
})
.doOnCompleted(() -> {
viewHolder.sourceListView.setAdapter(new BuildPlaylistContentAdapter(
BuildPlaylistStep2Activity.this,
-1,
sourceList));
});

}

@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
touchFlag = true;
selected_item = v;
viewParams = v.getLayoutParams();
break;
case MotionEvent.ACTION_UP:
selected_item = null;
touchFlag = false;
break;
default:
break;
}
return false;
}

private Observable<KalturaVideo> getSourceListObservalbe(String kalturaPlaylistId){
Observable<String[]> targetIdList = Observable.just(targetList)
.map((List<KalturaVideo> kalturaVideos) -> {
if(targetList == null){
return new String[]{};
}
String[] result = new String[kalturaVideos.size()];
int index = 0;
for (KalturaVideo item : kalturaVideos) {
result[index] = item.getId();
}
return result;
});
return Observable.zip(
targetIdList,
KalturaVideoRetriver.getVideoList(BuildPlaylistStep2Activity.this, kalturaPlaylistId),
(String[] idListOfTarget, KalturaVideo kalturaVideo) -> {
for (String item :idListOfTarget){
if(item.equals(kalturaVideo.getId())){
return null;
}
}
return kalturaVideo;
})
.filter(kalturaVideo -> {
return kalturaVideo != null;
});
}

public class ViewHolder{
ListView sourceListView;
ListView targetListView;

public ViewHolder() {
this.sourceListView = (ListView)findViewById(R.id.source_listview);
this.targetListView = (ListView)findViewById(R.id.target_listview);
}
}
}


getSourceListObservalbe - just removes from videos, which gets me KalturaVideoRetriver.getVideoList, videos which contained in targetList


As you can see from code, I try to subscribe on Observable in onPostCreate method and display data on listview, but nothing happens, and I don't know why...


Map Fragment shows as visible despite android:visibility="gone"

I'm working on an alternative simplified layout for an app that is used for smaller screens. This layout should not include a map fragment that is used in the larger layout, however, I'm supposed to avoid programmatic changes if at all possible. The activity that shows the layout also does stuff with the fragment using its ID, so I can't just delete it. I tried making the fragment invisible, like this:



<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />


But the fragment remains visible. The same happens when I set the visibility to "invisible". The fragment's default position is partially hidden by a view, but when I move the fragment around the layout, it still shows up as visible wherever I put it.


Is there a reason the fragment ignores the visibility parameter? Is there another non-programmatic solution?


Android Studio Portable

Is it possible to create a fully Portable Android Studio environment without having to install things on my Windows based Computer with the following packages?



  • Portable OpenJDK

  • Zip Version of Android Studio

  • Zip version of Android SDK


Android 5.1 push notification icon is blank

When using Parse for push notifications our app always displayed the application's launcher icon. In the latest Android 5.1 version, the icon appears to be blank (a white square).


I tried setting the icon in the meta data:



<meta-data android:name="com.parse.push.notification_icon" android:resource="@drawable/noti_icon"/>


Based on the question here


But nothing seems to work. Any ideas?


Progress bar inside custom dialog fragment - How to pass progress from an AsyncTask?

I have created a custom dialog fragment, inside it I have placed a progress bar. The host activity has an AsyncTask which uploads some images to a server. What I need is a way to pass the progress to the progress dialog fragment, I have tried via variables but it launches the fragmet again and again as the progress changes.


How could I pass the progress values without re launching the dialog fragment while values are changing?


I have tried with an interface as well, but it won't initialise my listener (the listener is always null).


my asyncTask (loopj):


private UploadProgressListener progressListener;



public interface UploadProgressListener {
public void onProgress(int position, int length);
}

//Interface to send selected image's position for deletion
public void setUploadProgressListener(UploadProgressListener listener) {
this.progressListener = listener;
}


....



client.post("http://ift.tt/1G7kFqj", params,
new AsyncHttpResponseHandler() {

@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
System.out.println("Upload failed!" + arg3
+ " statys code: " + arg0);
if (arg0 == 0) {
System.out.println("Retrying Upload!");
sendZip();
}
}

@Override
public void onProgress(int position, int length) {

if(progressListener != null){
progressListener.onProgress(position, length);
}

}

@Override
public void onStart() {

// Show preloader dialog
DialogFragment newFragment = new PreloaderDialog();
newFragment.show(getSupportFragmentManager(),
"preloader");
}

@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
System.out.println("Success!");
Toast.makeText(context, "Multumim pentru Comanda!",
Toast.LENGTH_LONG).show();
finish();
datasource.deleteAllRows();
}
});


and the progress dialog fragment:



public class PreloaderDialog extends DialogFragment implements UploadProgressListener {

private Builder v;
private ProgressBar uploadProgress;
int position;
int length;

/*
public PreloaderDialog() {
this.position = position;
this.length = length;
}
*/

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.preloader_dialog, null);

builder.setView(view);

OrderActivity progressChanged = new OrderActivity();
progressChanged.setUploadProgressListener(new UploadProgressListener() {

@Override
public void onProgress(int position, int length) {
System.out.println("changed");

}
});

uploadProgress = (ProgressBar) view.findViewById(R.id.uploadProressbar);

// Create the AlertDialog object and return it
return builder.create();
}


@Override
public void onProgress(int position, int length) {
//uploadProgress.setMax(length);
// uploadProgress.setProgress(position);
//System.out.println("progresspos: " + position);

}

:app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION:

I am building my project and after i add some codes from facebook for integration I faced :app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION: errors


Below is my build.gradle coding



apply plugin: 'com.android.application'


android { compileSdkVersion 20 buildToolsVersion "21.1.2"



repositories {
mavenCentral()
}

defaultConfig {
applicationId "com.hong.iqfunguess"
minSdkVersion 9
targetSdkVersion 21
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
} }


dependencies {



compile 'com.android.support:appcompat-v7:20.0.0'
compile 'com.android.support:support-v4:20.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile project(':facebook') }


The errors is show as listed below


Error:Execution failed for task ':app:dexDebug'.



com.android.ide.common.internal.LoggedErrorException: Failed to run command: E:\Android SDK\build-tools\21.1.2\dx.bat --dex --no-optimize --output C:\Users\Admin\Desktop\IQFunGuess April19\app\build\intermediates\dex\debug --input-list=C:\Users\Admin\Desktop\IQFunGuess April19\app\build\intermediates\tmp\dex\debug\inputList.txt Error Code: 2 Output: UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define Lbolts/AggregateException; at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596) at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554) at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303) at com.android.dx.command.dexer.Main.run(Main.java:246) at com.android.dx.command.dexer.Main.main(Main.java:215) at com.android.dx.command.Main.main(Main.java:106)



What's the problems? Thank you.


Read and write arrayList of Objects by using HashMap

I want to write and read 'HashMap' to file.


My 'HashMap' is:



Map<String, ArrayList<Descipline>> mapDis = new HashMap<String, ArrayList<Descipline>>();


and I write to file like this:



String root = Environment.getExternalStorageDirectory().toString();

Properties properties = new Properties();

for (Map.Entry<String, ArrayList<Descipline>> entry : mapDis.entrySet()){
properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream(root + "/myMap.txt"), null);


But I don't know how to read it.



Map<String, ArrayList<Descipline>> load = new HashMap<String, ArrayList<Descipline>>();

Properties properties1 = new Properties();

properties1.load(new FileInputStream(root + "/myMap.txt"));

for (String key : properties1.stringPropertyNames()){
//something will be here to read file
}

Getting an invalid output java

i developed a java program for my android , which will solve the one variable linear equation . String st1 = "4x-2+2x=8" ; if i give the above string as input or any one variable linear equation i got error , no result being got. equatin= Onevariable(st1);


tried a lot and didn't get the problem in this program.



public static String Onevariable (String eqn)
{
float ans = 0;
float coeffSum = 0;
float constSum = 0;
float coeffx[] = new float[100];
float[] constant = new float[100];
// System.out.println(eqn);
for (int i = 0, j = 0, k = 0; i < eqn.length() - 1;)
{
if (eqn.charAt(i + 1) == 'x' && i < eqn.indexOf("="))
{
if (i != 0 && eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
coeffx[j++] = n;
}
} else

{
String x = eqn.substring(i, i + 1);

if (x != "+" && x != "-")

{
int n = Integer.parseInt(x, 10);

coeffx[j++] = n;
}
}

i += 3;
}
if (eqn.charAt(i + 1) == 'x' && i > eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
coeffx[j++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
coeffx[j++] = n;
}
}
i += 3;
}
if (eqn.charAt(i + 1) != 'x' && i < eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
constant[k++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
constant[k++] = n;
}
}
i += 2;
}
if (eqn.charAt(i + 1) != 'x' && i > eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
constant[k++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
constant[k++] = n;
}
}
i += 2;
}
}
for (int i = 0; i < coeffx.length; i++)
coeffSum += coeffx[i];
for (int i = 0; i < constant.length; i++)
constSum += constant[i];
ans = constSum / coeffSum;
//System.out.println("Value of x = " + (-ans));
String s = Float.toString(-ans);
return s;
}

android PPM audio library

I need to implement audio PPM (Pulse Position Modulation) on android


Reference: http://ift.tt/PdoAGi


I want to output PPM from the audio output of the smartphone. The final scope is to create a joystick for radiocontrol. but this library may have many future purposes (follow me, lightbridge, etc.etc.). The radios commonly have a PPM output. Transmitters (and pc flight simulators) commonly have PPM input. My scope is to replace the radio with an android device. I wish to know if there is some piece of code ready to use or should i start from scratch?


EDIT: I found some points where to start


1) smartpropplus is a windows software that receives PPM audio and decodes it http://ift.tt/1OTf5vR


2) this is how PPM is structured: http://ift.tt/1DSNF5u


3) this is a easy image that explains how the signal is structured: http://ift.tt/1DSNF5w


I calculated that sampling the audio signal at 22000Hz will be sufficient to achieve a good resolution for each channel (22 steps for each channel)


EDIT: I started to write the class, cause no one of you wrote a solution. actually this test application outputs a sine waveform frame. now it misses the functions to set the channels inside frame. i ear strange noise over the sine waveform, and i'm not sure which is the reason why:


this is the class PPMencoder



package com.tr3ma.PPMencoderProject;

import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.os.AsyncTask;

public class PPMencoder {

int samplingRate=44100;

//private int bufferSize ;
private int streamBufferSize = (int)(samplingRate* 0.0225); // 22KHz * 22,5ms
public AudioTrack audioPlayer ;
AudioManager audioManager;
private boolean started;
private byte[] frame;

public PPMencoder(Context context) {

//bufferSize= AudioRecord.getMinBufferSize(samplingRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);

//set volume to max
audioManager=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int tmpVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, tmpVol, 0);
frame=new byte[streamBufferSize*2]; //doubled cause each sample is 1 integer

}

public int setSamplingRate(int freq) {
//we can change the sampling frequency in case it is not supported
samplingRate=freq;
//bufferSize = AudioRecord.getMinBufferSize(samplingRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);

//if (!(bufferSize>0)){
// //the sampling frequency is not supported
// return -2;
//}
streamBufferSize = (int)(samplingRate* 0.0225); // 22KHz * 22,5ms
frame=new byte[streamBufferSize*2];
return 0;

}

public int startGeneration(){
try {
//if (!(bufferSize>0)){
// //the sampling frequency is not supported
// return -2;
//}



//start the loop that sends out the data continuously
started=true;
StreamAudio streamAudio;
streamAudio=new StreamAudio();
streamAudio.execute();

return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}

public int stopGeneration(){
try {
started=false;
if (audioPlayer==null) return 0;
audioPlayer.stop();
audioPlayer.flush();
audioPlayer.release();
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}

public int setTestFrame() {
int tmpIndex=0;
float tmpVal;

//let's generate a sine at 2kHz
int sineFreq=2000;
for (int i = 0;i<frame.length;i=i+2){
tmpVal = (float) Math.sin( (float)tmpIndex * ((float)(2*Math.PI) * sineFreq / samplingRate)); //the part that makes this a sine wave....
short tmpVal1 = (short) (tmpVal * 32767);
frame[i] = (byte) (tmpVal1 & 0x00FF);
frame[i+1] = (byte) ((tmpVal1 & 0xFF00) >> 8);
tmpIndex=tmpIndex+1;
}

return 0;

}

public class StreamAudio extends AsyncTask<Void, Double, Void> {

@Override
protected Void doInBackground(Void... arg0) {
AudioTrack audioPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, samplingRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, frame.length, AudioTrack.MODE_STREAM);


//set volume of audioplayer to max
audioPlayer.setStereoVolume((float)1.0,(float)1.0);

if(audioPlayer.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)
audioPlayer.play();


//feed the speakers with our audio, by continuously send the PPM frame
while (started) {
try {
//if ( audioPlayer.getState() != AudioTrack.STATE_INITIALIZED){
audioPlayer.write(frame, 0, frame.length);
//}

} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
}


and this is the activity class used to test the library:



package com.tr3ma.PPMencoderProject;

import android.os.Bundle;
import android.app.Activity;
import com.tr3ma.PPMencoderProject.R;

public class Test extends Activity {

PPMencoder ppmencoder;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);

ppmencoder=new PPMencoder(this);

//Just for test, let's feed the audio with a sine waveform
ppmencoder.setTestFrame();

//start the generation of the signal through the speakers
int result=ppmencoder.startGeneration();
if (result==-2){
//sampling frequency not allowed, you can ask the user to change it
}
if (result==-1){
//error occoured, something went wrong
}




}

@Override
protected void onDestroy() {
super.onDestroy();
int result=ppmencoder.stopGeneration();
if (result!=0){
//error occoured, something went wrong
}
}
}


and this is the manifest file:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.tr3ma.PPMencoderProject"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.tr3ma.PPMencoderProject.Test"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

when I click button 4 I get a big run time error

This is a small android code to implement an exammple of actionlistener


To test this plz install this in your phone.


then first click button 4


then click button 10 and you will get the error.


This program has been written in adt.


enter code here



package com.example.test;
import java.util.Random;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
Button b[];

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b=new Button[11]; //declared an array of buttons and defined each button.

b[0] = (Button) findViewById(R.id.btn1);
b[1] = (Button) findViewById(R.id.btn2);
b[2] = (Button) findViewById(R.id.btn3);
b[3] = (Button) findViewById(R.id.btn4);
b[4] = (Button) findViewById(R.id.btn5);
b[5] = (Button) findViewById(R.id.btn6);
b[6] = (Button) findViewById(R.id.btn7);
b[7] = (Button) findViewById(R.id.btn8);
b[8] = (Button) findViewById(R.id.btn9);
b[9] = (Button) findViewById(R.id.btn10);
b[10] = (Button) findViewById(R.id.btn11);

for(int i=0;i<10;i++)
{
b[i].setOnClickListener(this);//set onClickListener on all buttons (here is where I think the execution is going wrong)
}

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


@SuppressLint("ShowToast") @Override
public void onClick(View v){

if(v.getId() == R.id.btn10)
{
Toast.makeText(getApplicationContext(), "Click a button to change its color", 3).show(); //displaying a message
if(v.getId() == R.id.btn1) //checks which button is clicked
{
b[0].setBackgroundColor(Color.GREEN); //on clicking this command will get executed
}
else if(v.getId() == R.id.btn2)
{
b[1].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn3)
{
b[2].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn4)
{
b[3].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn5)
{
b[4].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn6)
{
b[5].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn7)
{
b[6].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn8)
{
b[7].setBackgroundColor(Color.GREEN);
}
else if(v.getId() == R.id.btn9)
{
b[8].setBackgroundColor(Color.GREEN);
}
else
{
Toast.makeText(getApplicationContext(), "You clicked a wrong button", 3).show();
}
}
else if(v.getId() == R.id.btn11)
{
Toast.makeText(getApplicationContext(), "Randomly a button will change color", 3).show();
Random r = new Random();

for(int i = 0 ; i < 10 ; i++)
{
int i1 = r.nextInt(9);
b[i1].setBackgroundColor(Color.GREEN);
}

}
else
{
Toast.makeText(getApplicationContext(), "Select only btn10 and btn11", 3).show();
}
}
}

android spinner doesn't show indicator for android verison lesser than 5.0

I'm using the AppCompat, the EditText uses the material desgin style with a single indicator below it, but my problem is with the spinner it shows nothing except selectableItemBackground icon, that is the drop down icon. If i use a custom background drawable with a line shape, then the drop down icon doesn't show again. I really don't know if i have used the best words to explain my problem but i will be glad if someone can help out.



<Spinner
android:id="@+id/hb_sign_up_sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:layout_marginStart="10dip"
android:layout_marginEnd="10dip"
android:layout_marginRight="10dip"
android:textSize="16sp"
/>


The Item and SubITem is a spinner but it has no indicator. Even when i run it on my phone


Not able to show all data fetch from sqlite db into Expandable list view

I am inserting data from .csv file into sqlite database. But when I am fetching data from sqlite & showing it into Expandable list view,it skips some row data and showing in Expandable list view i.e. Some data is missing while showing from sqlite to Expandable list view


Main Activity



databaseHelper = new DatabaseHelper(this);
listDataHeader = new ArrayList<String>();
childDataHashMap = new HashMap<String, List<ChildInfo>>();
// get the listview
expListView = (ExpandableListView) findViewById(R.id.expandableListView);

// ****************************Group data******************************//
Cursor cursor = databaseHelper.getExpandableData();
cursor.moveToFirst();
Log.i(TAG, "cursor.getCount()" + cursor.getCount());
do {
Log.d(TAG,"Category "+ cursor.getString(cursor .getColumnIndex("categorydesc")));
String categoryDescription = cursor.getString(cursor .getColumnIndex("categorydesc"));
int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryId"));
Log.i(TAG, "categoryDescription:" + categoryDescription);
listDataHeader.add(categoryDescription);

// ****************************Child data******************************//
Cursor cursorChild = databaseHelper.fetchChildren(categoryId);
List<ChildInfo> childList = new ArrayList<ChildInfo>();
cursorChild.moveToFirst();
while (cursorChild.moveToNext()) {
String businessName = cursorChild.getString(cursorChild .getColumnIndex("BusinessName"));
phoneNumber = cursorChild.getString(cursorChild.getColumnIndex("ph_Phone"));
String landMark = cursorChild.getString(cursorChild.getColumnIndex("LandMark"));
Log.w("", "Category Child " + businessName);
ChildInfo childInfo = new ChildInfo(businessName, phoneNumber,landMark);
childList.add(childInfo);
}
childDataHashMap.put(categoryDescription, childList);
} while (cursor.moveToNext());
cursor.close();
listAdapter = new ExpandableListAdapterNew(this, listDataHeader,childDataHashMap);
// setting list adapter
expListView.setAdapter(listAdapter);


Database Helper



public Cursor fetchGroup() {
String query = "SELECT DISTINCT CategoryId, categorydesc FROM Category ";
Cursor res = db.rawQuery(query, null);
return res;
}

public Cursor getExpandableData() {
String query = "SELECT * FROM Category GROUP BY categorydesc";
return db.rawQuery(query, null);
}


Logcat output



Number of Records(10600): :: 11
MainAcitivity(10600): cursor.getCount()6
Category Hotels
categoryDescription:Hotels
Category Child GoodLuck
Category Restaurants
categoryDescription:Restaurants
Category Child ByThe Way
Category School
categoryDescription:School
Category Child Ornellas
Category Stationary
categoryDescription:Stationary
Category Child Venus
Category super shopee


Actual categories are 6 but it's showing only 5 of them.


How to play live MP3 url in android media Player class?


static MediaPlayer mPlayer;
Button buttonPlay;
Button buttonStop;
String url = "http://ift.tt/1H2lHXG";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
});

buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
}
}
});
}

protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}


I am trying to play live audio from this url "http://ift.tt/1H2lHXG" but when ever i tried to play it it shows mediaPlayer(-38,0) error.This url plays well in VLC player and vitamio but i wanna use android mediaplayer to play these kind of live urls


Google Glass Fullscreen Custom Layout Cards

I have an issue. Since the Card class is deprecated and the CardBuilder.EMBED_INSIDE is fairly limited. The only option is to use a custom View. I'd also like to use the CardScrollView and the CardScrollAdapter.


visit Google Glass Immersion Custom Layout without CardBuilder.Layout.EMBED_INSIDE


But my problem is, I can't have multiple views.


Here is MyCustomViewClass:



public class MyCustomView extends FrameLayout{
public MyCustomView (Context context) {
super(context);
initView();
}

private void initView()
{
View view = inflate(getContext(), R.layout.imageview, null);
addView(view);

View view2 = inflate(getContext(), R.layout.secondview, null);
addView(view2);
}


And thats my main activity class:



public class InspectionActivity extends Activity {

private CardScrollView mCardScroller;
private GestureDetector mGestureDetector;
private View mView;
private CardScrollView _cardScroller;
private ArrayList<View> _cardsList;
private MyCustomView _myView;
protected List<CardBuilder> mCards;
@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createCards();
_cardsList = new ArrayList<View>();
_myView= new MyCustomView (this);
_cardsList.add(_myView);
_cardScroller = new CardScrollView(this) ;
MainCardsScrollAdapter adapter = new MainCardsScrollAdapter(_cardsList);
_cardScroller.setAdapter(adapter);
_cardScroller.activate();
setContentView(_cardScroller);
}

private void createCards() {
mCards = new ArrayList<CardBuilder>();
}
public class MainCardsScrollAdapter extends CardScrollAdapter
{
ArrayList<View> _cardsList;
public MainCardsScrollAdapter(ArrayList<View> cardsList)
{
_cardsList = cardsList;
}

@Override
public int getCount() {
return _cardsList.size();
}

@Override
public Object getItem(int i) {
return _cardsList.get(i);
}


@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return _cardsList.get(i);
}

@Override
public int getPosition(Object o) {
return _cardsList.indexOf(o);
}

@Override
public int getViewTypeCount() {
return CardBuilder.getViewTypeCount();
}

@Override
public int getItemViewType(int position){
return 2;//should be changed, it's just an example
}
} }

android Asynctask thread.sleep?

In my app when user writes wrong character,my edittext becomes red then it becomes write.Actually ı am trying to make a red blink.This is my working code



class BlinkTask extends AsyncTask<EditText, Boolean, Boolean>
{

@Override
protected Boolean doInBackground(EditText... params) {

EditText et1=params[0];

try {
et1.setBackgroundColor(Color.RED);
Thread.sleep(1000);

} catch (InterruptedException e) {
e.printStackTrace();
}

try {
et1.setBackgroundColor(Color.WHITE);
}
catch (Exception e)
{
e.printStackTrace();
}

return true;
}
}


but when I take et1.setBackgroundColor(Color.WHITE); out of try-catch block.It gives no error but unfortunately myapp has stopped.I checked loggat but saw nothing.this is false code class BlinkTask extends AsyncTask {



@Override
protected Boolean doInBackground(EditText... params) {

EditText et1=params[0];

try {
et1.setBackgroundColor(Color.RED);
Thread.sleep(1000);

} catch (InterruptedException e) {
e.printStackTrace();
}


et1.setBackgroundColor(Color.WHITE);



return true;
}
}


I don't know why it needs try-catch although it gives no error.


also ı want to ask creating a asynctask class for this task is a good solution or nwhat else can be done.thank you


Unable to use android.support.v7.widget.toolbar

I'm trying to change status bar color in my application. For this I set MainActivity.java theme to "Theme.NoTitleBar.Fullscreen". Now, in my activity_main.xml, I create a frame layout followed by action bar. The project seems fine without errors but when I run it, the app crashes. Logcat shows something like.."unable to find class android.support.v7....". I added appcompat v7 library to my project but not sure whether i done it correctly. I'm a beginner, please help me.


activity_main.xml



<LinearLayout
xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.saregama.MainActivity"
android:orientation="vertical"
android:background="#1A1A1A">


<FrameLayout

android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#3D3D99">

</FrameLayout>



<android.support.v7.widget.Toolbar
xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3D3D99"
></android.support.v7.widget.Toolbar>



<ListView
android:dividerHeight="1dp"
android:divider="#000000"
android:padding="10dp"
android:layoutAnimation="@anim/layout_bottom_to_top_slide"
android:smoothScrollbar="true"
android:animationCache="false"
android:scrollingCache="false"
android:id="@+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />


</LinearLayout>

Android Application not running on all devices

My android application is running on 4.2.2 but not on 4.0.4 and 5.0. The minimum sdk version is 14 and target sdk version is 21.


So what can be done in order to run my application on most of the android devices..Any help would be really appreciated.Thanks in Advance:-)


Preferences hide toolbar

Solved with http://ift.tt/1H2lFPo


I've an issue with my preferences screen. If anyone have an idea of the problem. I've test many things but i don't really understand layout with preference fragment...


Activity_settings.xml



<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd"
android:id="@+id/toolbar"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:navigationContentDescription="@string/abc_action_bar_up_description"
android:background="?attr/colorPrimary"
app:navigationIcon="?attr/homeAsUpIndicator"
app:title="@string/action_settings"
/>


Preferences.xml



<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://ift.tt/nIICcg"
android:layout="@layout/activity_settings">
<EditTextPreference android:title="Your Name"
android:key="username"
android:summary="Please provide your username"></EditTextPreference>
<CheckBoxPreference android:title="Application Updates"
android:defaultValue="false"
android:summary="This option if selected will allow the application to check for latest versions."
android:key="applicationUpdates" />
<ListPreference android:title="Download Details"
android:summary="Select the kind of data that you would like to download"
android:key="downloadType"
android:defaultValue="1"
android:entries="@array/listArray"
android:entryValues="@array/listValues" />
<PreferenceScreen
android:title="Test de merde"
android:summary="Lolilol de merde">

<intent android:action="android.intent.action.VIEW"
android:data="http://www.android.com" />

</PreferenceScreen>
<PreferenceScreen
android:title="Bonjour"
android:summary="Hello"
android:key="user">
</PreferenceScreen>
</PreferenceScreen>


MyPreferencesActivity.java



package activity;

import android.app.FragmentManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.example.pierre.tan.R;

/**
* Created by dev on 19/04/15.
*/
public class MyPreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
Toolbar bar;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
LinearLayout root = (LinearLayout) findViewById(android.R.id.list).getParent().getParent().getParent();
bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.activity_settings, root, false);
root.addView(bar, 0); // insert at top
} else {
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
ListView content = (ListView) root.getChildAt(0);

root.removeAllViews();

bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.activity_settings, root, false);


int height;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
height = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}else{
height = bar.getHeight();
}

content.setPadding(0, height, 0, 0);

root.addView(content);
root.addView(bar);
}

bar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}






public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);

Preference userButton = (Preference) findPreference("user");
userButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
Intent intent = new Intent(getActivity(), ChangelogActivity.class);
startActivity(intent);
return true;
}
});
}
}

}


And a screenshot to show my problem: http://ift.tt/1DWyA2P


Thank you for all :)


Android Studio with Facebook (Login+Share Function)

I am a beginner who making an android app by using android studio which need Facebook login+share function.


To add a Share button add the following code snippet to your view:



ShareButton shareButton = (ShareButton)findViewById(R.id.fb_share_button);
shareButton.setShareContent(content);


I don't understand my view is in which class? Where actually should i put the code?


Thank you in advance.


Android - Clearing Navigation Backstack

I have 4 pages.


From page_1 > page_2 > page_3 > page_4.


Once the user reaches page_3 and clicks a button, it navigates to page_4. Once the button is clicked, I want to clear all the navigation history so when the user goes back on page_4, the app quits rather than going back to page_3.


I've tried:



Intent intent = new Intent(this, page_4.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();


But nothing happens. I can still go back to page_3, page_2 etc. How do I make it so that when the user clicks on the button on page_3, he goes to page_4 and from page_4 there shouldn't be any navigation history?