vendredi 29 mai 2015

Send data and wait for the answers with the Wearable Data Layer API

I have a wearable device from which data is sent to a handheld device wrapped in a DataMap object. On the handheld device I implemented a listener service that extends WearableListenerService implemented in this way:

public class ListenerService extends WearableListenerService {
    private static final String TAG = ListenerService.class.toString();

    private static final String WEARABLE_DATA_PATH = "/wearable_data";

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        DataMap dataMap;

        for (DataEvent event : dataEvents) {
            if (event.getType() == DataEvent.TYPE_CHANGED) {
                String path = event.getDataItem().getUri().getPath();

                if (path.equals(WEARABLE_DATA_PATH)) {
                    dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();

                    messageReceived(dataMap);
                }
            }
        }
    }

    private void messageReceived(DataMap dataMap) {
        Log.v(TAG, "DataMap received on handheld device: " + dataMap);
    }
}

The transmission from wearable to handheld works flawlessly. However, I would need to send back from handheld to wearable an answer, like "ok done" or "error xxx". How can I do that?

Android: Magnetometer data deviates

I am trying to estimate heading from the accelerometer, gyro and magnetometer data. I have implemented A Complementary Filter from here.

What I am trying is that I am holding the phone in my hand and I walked 15 steps in a straight line and I am trying to estimate Euler angles as given in the link above. But when I plot the raw data, I observe that the magnetometer data deviates. Here are the images of raw sensor data.

enter image description here

enter image description here

enter image description here

My question is: how do I estimate Euler angles so that they indicate I am walking in straight line.

OnClick / OnTouch user changing their mind

I am currently experimenting with onclick listeners and on on touch listeners.

I found out that using a onclick the app will always execute the action even if the user drags his/her finger off of the element. but i wanted the user to be able to change his mind and drag his/her finger off of the element so that it won't execute the action. i managed to do this with on touch.

on touch code :

action_bar_group_info.setOnTouchListener(new View.OnTouchListener() {
        int [] location = new int[4];
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            location[0] = action_bar_group_info.getLeft();
            location[1] = action_bar_group_info.getTop();
            location[2] = action_bar_group_info.getBottom();
            location[3] = action_bar_group_info.getRight();

            Log.v("Location: ", "top: "+String.valueOf(location[1]) + " left: "+String.valueOf(location[0]) + " right: "+String.valueOf(location[3]) + " bottom: "+String.valueOf(location[2]));
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                action_bar_group_info.setBackgroundColor(Color.parseColor("#ec9169"));
                return true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if ((int) event.getX() > location[0] && (int) event.getX() < location[3] && (int) event.getY() > location[1] && (int) event.getY() < location[2]) {
                    action_bar_group_info.setBackgroundColor(Color.parseColor("#ec9169"));
                    Intent intent = new Intent(mContext, GroupInformation.class);
                    intent.putExtra("gid", gid);
                    intent.putExtra("gname", gname);
                    intent.putExtra("image", img);
                    intent.putExtra("uid", uid);
                    startActivity(intent);
                    finish();
                }else {
                    action_bar_group_info.setBackgroundColor(Color.parseColor("#f54c00"));
                }
            }
            if(event.getAction() == MotionEvent.ACTION_MOVE){
                Log.v("Location pointer: x:"+ String.valueOf((int) event.getX())," Y: "+ String.valueOf((int) event.getY()));
                if ((int) event.getX() < location[0] || (int) event.getX() > location[3] || (int) event.getY() < location[1] || (int) event.getY() > location[2]) {
                    action_bar_group_info.setBackgroundColor(Color.parseColor("#f54c00"));
                }
            }

            return false;
        }
    });

But is this really the way to do it isn't there a easier way to achieve what i want?

action_bar_group_info is a linear layout.

System application in Android

How exactly Android determines if an application is a system application with root privilege?

I know that for such applications, ApplicationInfo.FLAG_SYSTEM will be enabled, and those applications must declare shared user id as "android.uid.system" in their Manifest file. Along with that there is another criteria, where an application located in /system/app should also be treated as System application.

I searched the source code for PackageMangerService.java in AOSP where I observed that if shared user id is android.uid.system then the application is assigned the flag as FLAG_SYSTEM.

But I guess, the applications which are available in /system/app do not contain the shared user id as android.uid.system then how do they get this flag FLAG_SYSTEM enabled for them?

Status of multicast on Android devices as on 2015

Multicast support on Android is Version specific ? Most of new age devices will come with 4.3 & above. So MulticastSocket API work on 4.3 & above ? Is multicast support is device/OEM specific ?

Wanted to know exact status whether Multicast on Android is supported as on May15 ?

Referred number of posts but it is not clear

http://ift.tt/1JbK4l6

Multicast RTP on Android 4.0+

Problem with MulticastSocket on Java-Android

http://ift.tt/1FHCf4p

http://ift.tt/1y1QFaX

http://ift.tt/1FHCdcz

How to receive Multicast packets on Android

Problem with Android Multicast Sockets

Android, how to use the Accelerometer Sensors?

can someone help me understand the Accelerometer Sensor. I've read this and this overviews about the sensors and the motion sensor but i can't understand which movement triggers which sensor, (for an example the Sensor TYPE_ACCELEROMETER and Sensor event data SensorEvent.values[0] means Acceleration force along the x axis (including gravity).) what does that mean? which motion is it? So if anyone can help me, please all I want to know is to check if the phone is on a landscape orientation and standing vertically, and when the phone gets tilted to the front or backward. these are the 3 movements that I want to know, thanks

Hi I am woring for a Quiz App, so I need to call post rest services(json),below one is my sample code which is not working

I need to pass 3 thing as parameter 1-userid, 2-List questionids and 3- List answerIds. My Question is how to pass List Object not String or Json String here-

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("userid", "121213"));
    nameValuePairs.add(new BasicNameValuePair("questionsids", listobj);
    nameValuePairs.add(new BasicNameValuePair("answerIds", listObj));

    HttpClient httpclient=new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

Is There any other way to call the post rest service.How to resolve above one?

Thanks Ranjan.

Android application on version 2.3 freezing

I am running my application with webview (extended webChromeClient) on android 2.3.

In that webview I open a webpage, content of which like images keep on changing. Sometimes I notice, after approx 1.5 hours my webview freezes.

Can anyone provide me a solution or tell me why it is happening?

How to draw smooth movement on surface

I am trying to achieve smooth movement of a drawn object.
Here I draw circle which by itselfe move in Hypotrochoid path. I am setting delay in 16 ms to get 60 frames per second and position every frame. However my circle still does not move smooth. Main Activity

Handler handler = new Handler();
    Runnable runnable = new Runnable(){

        @Override
        public void run(){
            masterMotion.tryDrawing();
            handler.postDelayed(runnable, 16);

        }
    };


    @Override
    public void surfaceCreated(SurfaceHolder holder){
        masterMotion = new MasterMotion(MainActivity.this, holder);
        handler.postDelayed(runnable, 16);

    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int frmt, int w, int h){
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder){
        handler.removeCallbacks(runnable);
    }

Motion

public Motion(int type, int color, int xPos, int yPos, int radius, int totalHeight){
        this.type = type;
        this.color = color;

        this.radius = radius;
        xBottom = xPos;
        yBottom = yPos;
        xTop = xBottom;
        yTop =  (int) (radius * 0.2 - radius);
        xMid = xBottom;
        yMid = (int) (radius * 0.2 - radius + totalHeight / 2);
        xAlt = xBottom;
        yAlt=yBottom;
        switch(type){
            case 0:
                innerR = 20;
                hR = 10;
                hD = 2;
                break;


        }
    }


    public void drawMyStuff(final Canvas canvas, final Paint mPaint){
        updatePositions();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(color);
        canvas.drawCircle(xR, yR, radius, mPaint);

    }


    public void updatePositions(){
        xR =
            (float) (xAlt + (innerR - hR) * Math.cos(angle) + hD * Math.cos(
                                                                               ((innerR - hR) /
                                                                                    hR) *
                                                                                   angle
            ));
        yR =
            (float) (yAlt + (innerR - hR) * Math.sin(angle) + hD * Math.sin(
                                                                               ((innerR - hR) /
                                                                                    hR) *
                                                                                   angle
            ));
angle = (angle + 0.03) % (2 * Math.PI);

        if(stepCount>=0){
            xAlt+=stepX;
            yAlt+=stepY;
            stepCount--;
        }
    }


    public void goBottom(){
        mustMoove=true;
        direction =0;
        stepX = (xBottom-xAlt)/20;
        stepY = (yBottom - yAlt) /20;
        stepCount=20;

    }


    public void goMid(){
        mustMoove = true;
        direction = 1;
        stepX = (xMid - xAlt) / 100;
        stepY = (yMid - yAlt) / 100;
        stepCount=100;
    }


    public void goTop(){
        mustMoove = true;
        direction = 2;
        stepX = (xTop - xAlt) / 100;
        stepY = (yTop - yAlt) / 100;
        stepCount=100;
    }

}

AdMob Strange Behaviour

I have implemented Banner Ads in my App and now trying to implement Intertistial Ads.

I have successfully implemented the Intertistial Ads. But somehow Admob is behaving strange.

When an app is ideal for some time, user is directly taken to NewsHunt App Store Page. I don't know what to do. Please help,will Google block my account ?? Why this is happening !?

Unable to make toolbar transparent in Android

My tool bar always stays gray when I try to set the background as transparent. Here is my XML.

<android.support.v7.widget.Toolbar xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:minHeight="@dimen/abc_action_bar_default_height_material"
    app:theme="@style/Rushmore.Toolbar.Transparent" />

And my theme

 <style name="Rushmore.Toolbar.Transparent" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="android:windowActionBarOverlay">true</item>

        <!-- Support Library compability -->
        <item name="windowActionBarOverlay">true</item>
    </style>

I have tried it from code

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        toolbar.setBackgroundResource(Color.TRANSPARENT);

I am not sure what is it I am missing...

Getting same list for two tabs in tabs with listview on start of activity

So,I have this activity which has tabs with listviews in them, and the problems I'm facing are:

The first and second tabs are having the same content i.e. the content the second tab should have is in first and second tab.

The third tab has correct content, though this is because it only instantiates just first and second tabs initially. When I set
mViewPager.setOffscreenPageLimit(2);

all the three tabs have same content, which is that of the third tab.

But after i've scrolled to third tab and then scroll back to the first one, the first one refreshes and has correct content.

Also, the next problem is the second tab never refreshes,because its always on the right or left to the tab which is opened. I want the tabs to refresh every time they are opened since i'll be constantly changing the material in the lists.

package com.towntrot.anil.towntrot_eventmanager_02;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class SlidingTabsBasicFragment extends Fragment {

ListView list;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
public guestlist gg;
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private String[] eventtype={"CHECKED IN","CHECKED OUT","WAITING"};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_sample, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
    mViewPager.setAdapter(new SamplePagerAdapter());
    mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setViewPager(mViewPager);
}

class SamplePagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return o == view;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return eventtype[position];
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
                container, false);
        guestlist gg=(guestlist)getActivity();
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append(position);
        String strI = sb.toString();
        Toast.makeText(getActivity(),strI,Toast.LENGTH_LONG).show();
        setListData(gg.getNamelist(), gg.getStatuslist(), gg.getNo0fPeople(), position);
        list= ( ListView )view.findViewById(R.id.list);
        CustomAdapter adapter;
        adapter=new CustomAdapter( getActivity(), CustomListViewValuesArr);
        list.setAdapter(adapter);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

}
public void setListData(String[] string,String[] status,int no,int pos) {
    CustomListViewValuesArr.clear();
    for (int i = 0; i < no; i++) {

        final ListModel name = new ListModel();
        int x=Integer.parseInt(status[i]);
        if(pos==x){ name.setCompanyName(string[i]);
        CustomListViewValuesArr.add(name);}
    }
}


}

Please help me, I've seen a lot of answers but couldn't solve this. Any help is appreciated.

I can not save the value from EditText when closing of the fragment

I have a fragment with EditText. I enter text into EditText. I press the button. I open next fragment . Current fragment Replace. How can I save the data entered in the EditText and get them again when I go back to the first fragment? It suggests itself

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("code", getTextField().getText().toString());
        textCode = getTextField().getText().toString();
    }

but he did not call. I read and learned that it is called if I wring such a program. I checked and so called. But as I call it when I call a new fragment , and they Replace old? Or maybe there are other options to preserve the value? Static variable global, SHARED preferens - not good.

How to receive multiple UDP message using AsyncTasks?

I have written a UDP server using AsyncTasks. This is code for receiving UDP packet in Async Backgroung Process. My question is: How to modify this code to receive multiple message? My aim is to write a code which can simultaneously receive multiple message and can send message. thank you.

public class MainActivity extends Activity 
{
    public TextView tv;
    public TextView tv2;
    public TextView tv3;

    public MyAsyncTask myTask;

    int i =0;
    // String s;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

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


        Button button1 = (Button) findViewById(R.id.button1);
         tv = (TextView) findViewById(R.id.textView1);
         tv2 = (TextView) findViewById(R.id.textView2);
         tv3 = (TextView) findViewById(R.id.textView3);
        //TextView textMessage = (TextView) findViewById(R.id.textView2);

         myTask = new MyAsyncTask(this);
         myTask.execute("ppp");


        button1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) 
            {
                /*cheack ping message*/
                //boolean morgan= isOnline();
                //String s = String.valueOf(morgan);
                tv.setText("kkkkkkkkkk");   // print ping message

                Log.d("MyTag@","This is sample log message");

                //new MyAsyncTask(getApplicationContext()).execute("ppppp");

            }

        });




    }



    @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;
    }

    @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();
        if (id == R.id.one)
        {
            Toast.makeText(getApplicationContext(), "Toast Message ONE", Toast.LENGTH_LONG).show();

        }
        if (id == R.id.two)
        {
            Toast.makeText(getApplicationContext(), "Toast Message TWO", Toast.LENGTH_LONG).show();
        }
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }




}

class MyAsyncTask extends AsyncTask <String, Void, String>
{
     private Context context;
     public Activity mactivity;
     static String jj ="helooooooo";
    public MyAsyncTask(Activity a)
    {
        // TODO Auto-generated constructor stub
        this.mactivity = a;
    }

    @Override
    protected String doInBackground(String... params) 
    {
        try
        {
            byte[] inbuf = new byte[1000]; // default size
            DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
            Log.d("p2p", "3");
            DatagramSocket socket = new DatagramSocket(6000);

            socket.receive(packet);
            Log.d("p2p", "4");
            int numBytesReceived = packet.getLength();
            //System.out.println(numBytesReceived);
              jj = new String(inbuf);
            //System.out.println(s);
            //System.out.println(inbuf[2]);

            socket.close();


        }
        catch(Exception e)
        {
            Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
            e.printStackTrace() ;
        }


        Log.d("MyHello","doInBackground");
        return jj;
    }

     protected void onPostExecute(String result)
     {
         Log.d("MyHello","onPostExecute "+result);
         //context.;
         ((MainActivity) mactivity).tv3.setText(jj);

     }

}

App Lock Programatically

I have devepoled an android app i want to implement password for its use.

1)The password will be constant for all users. 2)People who knew the password can only access the app. 3) Here password is set by me (the app developer).

Now i am confuse on implementing this idea. I guess i need a file where i can store encrypted password read the file for validation. But the question is can I ship out my app with a file with encrypted password. Or shall i use SQLlite for this.

Thanks

QR-encode a String to Image in Android project using zxing

I am trying to create a simple Android app, which would display a QR-coded image - by using zxing library.

So I have installed HomeBrew, ant and maven at my Mac OS Yosemite notebook and pointed the ANDROID_HOME environment variable to the location of Android SDK.

Then I have checked out latest zxing from GitHub and built it (seeming without any errors) with the command mvn package (and using javac version 1.8.0_45).

After that I have created a new Android project with blank Activity in Eclipse and copied the 3 jar files into its libs directory:

  • android/libs/core-3.2.1-SNAPSHOT.jar
  • android-core/target/android-core-3.2.1-SNAPSHOT.jar
  • android/target/android-4.7.4.jar

Unfortunately, my simple code in MainActivity.java does not compile:

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

    ImageView imageView = (ImageView) findViewById(R.id.qrCode);
    String qrData = "Data I want to encode in QR code";
    int qrCodeDimention = 500;
    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, 
            null,
            Contents.Type.TEXT, 
            BarcodeFormat.QR_CODE.toString(), 
            qrCodeDimention);

    try {
        Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
        imageView.setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
    }
}

The errors are (here fullscreen):

eclipse screenshot

BarcodeFormat cannot be resolved
Contents cannot be resolved to a variable
QRCodeEncoder cannot be resolved to a type
QRCodeEncoder cannot be resolved to a type
WriterException cannot be resolved to a type

But at the same time I can see these (supposedly not found by Eclipse) classes by calling tar tool:

# tar tvfz libs/core-3.2.1-SNAPSHOT.jar | grep -i WriterException
-rwxrwxrwx  0 0 0 0 28 Mai 20:35 com/google/zxing/WriterException.class
# tar tvfz libs/core-3.2.1-SNAPSHOT.jar | grep -i BarcodeFormat
-rwxrwxrwx  0 0 0 0 28 Mai 20:35 com/google/zxing/BarcodeFormat.class
# tar tvfz libs/android-4.7.4.jar | grep -i QRCodeEncoder
-rwxrwxrwx  0 0 0 0 28 Mai 20:39 com/google/zxing/client/android/encode/QRCodeEncoder.class

What am I doint wrong please, why can't Eclipse find the classes?

I have asked my question at GitHub as well.

How to make a VideoView full screen by clicking a button in Android?

I have a VideoView in my fragment class. There is also a button that allows you to play and pause the video. When I click the button to play the video, I want to video to go full screen. How can I do this programatically and not through XML?

Here is my source for my fragment:

public class Test extends Fragment
{
    private VideoView vid;
    private Button    playpause1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        root = (ViewGroup) inflater.inflate(R.layout.test, null);

        vid = (VideoView) root.findViewById(R.id.videoView1);
        vid.requestFocus();
        vid.setVideoURI(Uri.parse("my_path"));

        playpause1 = (Button) root.findViewById(R.id.playpause1);
        playpause1.setText(R.string.buffering);
        playpause1.setEnabled(false);

        playpause1.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if vid.isPlaying())
                {
                    vid.pause();
                }
                else
                {
                   vid.start();
                }
            }
        });


       vid.setOnPreparedListener(new OnPreparedListener()
        {
            @Override
            public void onPrepared(MediaPlayer mp)
            {
                playpause1.setEnabled(true);

                mp.setOnInfoListener (new MediaPlayer.OnInfoListener()
                {
                    @Override
                    public boolean onInfo (MediaPlayer mp, int what, int extra)
                    {
                        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START)
                        {
                            playpause1.setEnabled(false);
                        }

                        if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END)
                        {
                            playpause1.setEnabled(true);
                        }
                        return false;
                    }
                });
            }
        });
    }
}

Call viewpager adapter's NotifyDataSetChanged from the child fragment

I'm trying to do a challange from Android Big Nerd Ranch book on using action bars. and i'm getting the below exception when i try to delete:

java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!

below is the code i handle the delete on CrimeFragment.java

 @Override
                       public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                           switch (item.getItemId())
                           {
                               case R.id.menu_item_delete_crime:
                                   CrimeLab.get(getActivity()).deleteCrime(mCrime);
                                   mode.finish();

                                    return true;
                               default:
                                   return false;
                           }

                       }

My target SDK is 21 ad the AVD is running lollipop. how do i get around this. much appreciate any help.

I know we can do as suggested in this post. but that would couple my fragment for the specific activity. anyway to overcome this ?

android autolink is too aggressive

Phones with SDK 20+ think that any two words with a dot between them is a link. How can I make my own Link detector ?

android:autoLink="web" thinks abra.kadabra is an url.

setAutoLinkMask(Linkify.WEB_URLS); thinks abra.kadabra is an url.

Phones with SDK < 20 link everything correctly, it's only 20+.

//-----Examples of what I've tried------

//Code happening inside my custom TextView
SpannableString ss = new SpannableString(this.getText().toString());
//LinkManager is a copy of Linkify but with another pattern.
LinkManager.addLinks(ss, LinkManager.WEB_URLS);
setText(ss);
setMovementMethod(LinkMovementMethod.getInstance());
setWebLinksTouchFeedback();

This didn't linkify anything. Even when I use Linkify instead of LinkManager

I have tried many other solutions, all who end up in linking nothing or everything. Any solution out there ?

Android device performance estimation techniques

I am developing an Android application and I am facing what I thought would be a common issue, but to my surprise there doesn't seem too be much documentation about it (or I didn't know how to search).

Basically, the issue is about estimating the performance of a device. In an activity, I have scenario where I can play an animation (fade out of multiple views), but in some devices the animation is overkill and makes the application run slow. So in that scenario, instead of playing the animation, I can set the visibility to INVISIBLE, which is far better performant but less appealing for the user.

My problem is in detecting when should I use the animation and when should I use the simple visibility change. I don't know how to detect it because this doesn't really depend on the SDK version, nor the phone model. I guess some indicators would be how much RAM is available or something like that. But I would like to know if there are any common techniques used for similar scenarios.

Is there another way to find a specific string in a database and obtain those results that match besides using the regular method?

I am trying to store the average ratings for various locations, but I need a way to find a specific string in a database and obtain those results that match the string other than the following method. Any help would be appreciated,

Jacob

Current method that I can't use (see my other posts):

query.whereContains("reviewName", titleRev);
query.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> scoreList, ParseException e) {
        if (e == null) {

ProgressBar ring cut in half

How can I cut the progressbar(ring) in half? in Android

http://ift.tt/1eCuMKU

http://ift.tt/zvZmCM

any suggestions?

contacts not showing in activity

I am trying to show contacts in an activity but its not working. I review my code, But not able to understand whats the problem is. Here is my code:-

/deleted/

showfriendlist.xml

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
        xmlns:tools="http://ift.tt/LrGmb4"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ListView
            android:id="@+id/lst_contacts"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

Google api client is not working in android wearable emulator

I am trying to implement sample project for Data Layer Api which comes with android SDK. My Problem is when I try to run sample app, I am getting error: "DataLayerListenerService failed to connect to GoogleApiClient, error code: 2" Can any one help me how to solve this problem? I am using Motorola E as a handheld device and emulator for android wearble device

Thank you

How to test elements on canvas in android through Robotium

I am trying to test elements on the canvas with robotium, but it is not working correctly

I am using SearchText() function to find the written text on the screen (canvas), but its not working

Is there any other way to test whether that string is present on the screen (canvas)

Talkback in Android will read all texts irrespective of layout type in dialogue modal?

I have got a table layout 3*3 in my dialogue modal with some TextViews. When I check with Talkback it reads all texts non-stop. Talkback reads all the texts in table from left to right in a particular row which is confusing for the listeners. I need it to read only when I tap on particular item.

Android runtime language change not reflecting in the previous activity

My application is supporting three languages English, Dutch and German. When I change the language at run time my current activity language changes, but my previous activity language are not translated. So how can I translate the previous activity when resume?

Accessing Android application data folder

I am building an application in which I want to use application specific data folder (the one with the application package name). I read a few documentation but they only confused me more.

There are a few question for which I need answers.

1. When is the application data folder created?
2. Where does this folder gets created? on internal storage of the device or on the sdCard or both?
3. What happens if we create the application data folder manually?
4. Does the app folder gets deleted if we uninstall the app?
5. What happens when we reinstall any app? will a fresh copy of app folder get generated.
6. Can we perform read/write operations on the database/sharedPrefernces inside the application data folder.

Android App isn't installed issue

I upgraded to Unity 5 and recompiled my game and executed to my device just fine. After editing the android manifest I am stuck with this issue:

Unity generates the APK, push into device but never executes it , then i manual tap to open the game and i get this message "Android App isn't installed"

I had a backup of the original manifest before editing. So I replaced the modified file with the backup, but the app still doesn't open !!!

Any help is highly appreciated.

Create Dynamic MultiLevel Treeview in Android

I want to Create A Dynamic TreeView Upto N_level. In WHich i Can Create A Xml Data Dynamically. SO i Can Add or Delete Node Dynamically. I tried With `ListView. I want to Create Simple Application. In That App I Want to Create XML file. For E.g.

<MYTAG>
    <Name>12
           <Value>32

setHomeButtonEnabled on toolbar in a fragment

Android studio 1.3
com.android.support:appcompat-v7:22.1.1

Hello,

I am using the new toolbar and displaying in my fragment. However, I want to be able to navigate back to the previous fragment by having the setHomeButtonEnabled(true). However, in my fragment in the onCreateView there is no such function. This works in the Activity, but doesn't work in the fragment.

Is there anyway to have the toolbar display the setHomeButtonEnabled so that an arrow is displayed so the user can nagivate back.

public class FileTransferFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_file_transfer, container, false);

        final Toolbar toolbar = (Toolbar)view.findViewById(R.id.app_bar);
        AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
        appCompatActivity.setSupportActionBar(toolbar);

    /* TRIED THIS BUT DIDN'T WORK */
        appCompatActivity.getActionBar().setHomeButtonEnabled(true);
        appCompatActivity.getActionBar().setDisplayHomeAsUpEnabled(true);
        return view;
    }
}

In my Activity I am extending the AppCompatActivity and using appcompat-v7:22.1.1

public class FileTransferActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_transfer);

        if(savedInstanceState == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fragment_container,
                    FileTransferFragment.getFileTransferFragment(1234), "FileTransferFragment");
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            fragmentTransaction.commit();
        }
    }
}

As you can see on the image there is no arraw on the left of the toolbar to allow the user to nagivate back. enter image description here

java.lang.IllegalArgumentException: Cannot determine the graph element type because the document class is null.

Hello I'm creating a widget for Samsung Gear. Im using Tizen IDE for wearable. I followed their youtube tutoria: How to Create a Basic Integrated Gear Application.

I tried Build Project in Tizen IDE and there was a build error:

Errors occurred during the build. Errors running builder 'Web Widget Builder' on project 'SimpleSAPConsumer'. Build Error : Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function Build Error : Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function

Then Error Log said:

eclipse.buildId=
java.version=1.7.0_67
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en
Command-line arguments:  -os win32 -ws win32 -arch x86_64

Error
Fri May 29 17:01:28 SGT 2015
Build Error :

java.lang.IllegalArgumentException: Cannot determine the graph element type because the document class is null. Probably this is a projection, use the EXPAND() function
        at com.tinkerpop.blueprints.impls.orient.OrientElementIterator.next(OrientElementIterator.java:49)
        at com.tinkerpop.blueprints.impls.orient.OrientElementIterator.next(OrientElementIterator.java:13)
        at org.tizen.common.builder.dependency.DependencyInDB.getVertexFromDB(DependencyInDB.java:236)
        at org.tizen.common.builder.dependency.DependencyInDB.containsVertex(DependencyInDB.java:254)
        at org.tizen.common.builder.BuildProcess.removeResource(BuildProcess.java:413)
        at org.tizen.common.builder.BuildProcess.build(BuildProcess.java:282)
        at org.tizen.web.project.builder.WebBuilder.build(WebBuilder.java:252)
        at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
        at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
        at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
        at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
        at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
        at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
        at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

How to make ListView's scroll slower when using smoothScrollToPosition() function?

Scroll of my ListView is very fast when using smoothScrollToPosition(int position) function. I want to customize this and want to make it slower.

I tried set android:fastscrollenabled="false" and setFriction(ViewConfiguration.getScrollFriction() * 5) but don't solve this problem. Can someone help me? Any help will be greatly appreciated! Thank in advanced :)

How to set boundary for moving views in android

how can we limit views inside the parent layout in android till now I am able to move views on touch event but I want to limit those views inside parent layout

Deep linking unable to get data in Activity - Android?

I am enabling deep linking in App. It is working pretty fine. but I am facing problem when the app is already opened in background.

Case 1 - if my activity is set to "singleTop" and running in the background, so,the moment I open the link from browser it redirects to the same activity and call onNewIntent().

but I am not getting any data in onNewIntent()

onNewIntent(){
    Uri data = getIntent().getData();
    // data = null
}

Case 2- if I remove "singleTop" then everything works fine, but creating more instances of Activity.

Did anybody face this issue? How can we solve the Case 1 issue?

Android contextual action bar with custom ListView not allowing multiple selection

I followed Android API guide implementing CAB and I have several problems:

  1. Multiple selection not exist
  2. Selected items (rows) not colored to indicate they are selected
  3. How to change: [A] color of the CAB [B] Show some text on the CAB

This is my code where MainListAdapter is "regular" implementation of custom ListView adapter, with custom view for each item, and dataList is simple data populate list with:

    listview = (ListView)findViewById(R.id.listview);
    listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            //Here you can do something when items are selected/de-selected, such as update the title in the CAB
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            //Respond to clicks on the actions in the CAB (contextual action bar)
            switch (item.getItemId()) {
                case R.id.menu_delete:
                    deleteSelectedItems();
                    mode.finish();  //Action done, so close the CAB
                    return true;
                case R.id.menu_open:
                    openSelectedItem();
                    mode.finish();  //Action done, so close the CAB
                    return true;
                default:
                    return false;
            }
        }

        private void openSelectedItem() {
            // TODO Auto-generated method stub

        }

        private void deleteSelectedItems() {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            //Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.listmenu, menu);
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            //Here you can make any necessary updates to the activity when the CAB is removed. By default, selected items are deselected/unchecked.
            //TODO refresh the list
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            //Here you can perform updates to the CAB due to an invalidate() request
            return false;
        }
    });

    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
            //TODO open DisplayActivity
            Toast.makeText(getApplicationContext(), "Open File", Toast.LENGTH_LONG).show();
        }
    });

    listAdapter = new MainListAdapter(dataList, context);
    listview.setAdapter(listAdapter);

android: List view edittext data loses on scrolling

I went through almost all the similar questions and tried what was suggested (didnt understand much). I want the listview having 2 edittexts to preserve the values even after becoming invisible after scrolling. And when the edittext losses focus, i want each edittext value to be saved in a arraylist (2 arraylist - one for quantites and one for prices). which i can later save to the database. I tried having the code in the OntextChanegd method, but it doesnt seem right.

please help as it is an urgent project i am working on thank you,

public class CustomAdapter extends BaseAdapter {
ArrayList<String> names;
Context context;
ArrayList<String> itemPrices = new ArrayList<>();
ArrayList<String> quantities = new ArrayList<>();

CustomAdapter(ArrayList v, Context c) {
    names = v;
    context = c;
}

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

@Override
public Object getItem(int position) {
    return names.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    try {
        final ViewHolder holder;
        // TODO Auto-generated method stub
        if (convertView == null) {
            holder = new ViewHolder();

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row, null);

            holder.textView = (TextView) convertView.findViewById(R.id.rowText);
            holder.editQty = (EditText) convertView.findViewById(R.id.qty);
            holder.editprice = (EditText) convertView.findViewById(R.id.price);
            holder.textView.setTextSize(20);
            holder.textView.setTextColor(Color.BLACK);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.ref = position;

        holder.textView.setText(names.get(position));
        holder.editQty.setHint("Quantity");
        holder.editprice.setHint("Price");
        holder.editQty.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        holder.editprice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



        return convertView;
    }catch (NumberFormatException ex){
        Toast.makeText(context,"!!!",Toast.LENGTH_SHORT).show();
        ex.printStackTrace();
    }


    return convertView;
}




private class ViewHolder {
    TextView textView;
    EditText editQty;
    EditText editprice;

    int ref;
}

}

How to get position of listitem using setonitemclicklistener and send to next activity

In my app I am getting response from server and displayint it in listview, now what I am trying is when user click on listitem it should get position of it and need to send it to next activity, but it is not working.

Following is mt snippet code

btn_go.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                        || connectivityManager.getNetworkInfo(
                                ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                // listView1.removeAllViews();
                listView1.setAdapter(null);
                arraylist_oper = new ArrayList<HashMap<String, String>>();

                // listView1.notify();
                new getOperationalControlList().execute();  
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    listView1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            // TODO Auto-generated method stub

            //qr =  ((String) listView1.getItemAtPosition(position)).toString();

            Intent intent=new Intent(OperationalControl.this,DispatchTracking.class);
            intent.putExtra("arrow_val", "2");
            intent.putExtra("qrcodes", qr);
            Toast.makeText(OperationalControl.this, qr, Toast.LENGTH_LONG).show();
            startActivity(intent);
        }
    });
}

class getOperationalControlList extends AsyncTask<String, String, String> {
    private String msg = "";
    int register_error = 1;

    JSONArray operation;
    JSONObject obc;
    String error;
    String access_token, office_name, office_id;
    String user_id;
    String name;
    private ProgressDialog progressDialog;


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(OperationalControl.this);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("Loading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setProgress(0);
        progressDialog.show();
        noresponse.setVisibility(View.GONE);

    }

    @Override
    protected String doInBackground(String... params) {
        JSONObject jsonObjSend;
        String content = null;
        arraylist_oper = new ArrayList<HashMap<String, String>>();
        try {

            consts.pref = getSharedPreferences("pref", MODE_PRIVATE);
            consts.editor = consts.pref.edit();
            String OperationalControlList_URL = ((consts.pref
                    .getString(consts.Base_URL,
                            consts.Base_URL)) + consts.OperationalControlList_URL);
            Log.d("OperationalControlList_URL url:",
                    OperationalControlList_URL);

            arraylist = new ArrayList<HashMap<String, String>>();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(OperationalControlList_URL);

            System.out.println("URL :-"
                    + consts.OperationalControlList_URL.toString());

            user_id = consts.pref.getString("user_id", "");
            access_token = consts.pref.getString("access_token", "");
            office_id = consts.pref.getString("office_id", "");
            date = date_dropdown.getText().toString();

            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(
                    5);

            nameValuePair.add(new BasicNameValuePair("user_id", user_id));
            nameValuePair.add(new BasicNameValuePair("access_token",
                    access_token));
            nameValuePair.add(new BasicNameValuePair("filter", filter));
            nameValuePair
                    .add(new BasicNameValuePair("office_id", office_id));
            nameValuePair.add(new BasicNameValuePair("date", date));

            // Encoding POST data
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();

                System.out.println("USER_ID : " + user_id.toString());
                System.out.println("access_token : "
                        + access_token.toString());
                System.out.println("filter : " + filter.toString());
                System.out.println("office_id : " + office_id.toString());
                System.out.println("date : " + date.toString());

                content = EntityUtils.toString(entity);

                Log.d("aaa", content);

                jsonObjSend = new JSONObject(content.toString());

                if (jsonObjSend.getString("status").equals("2")) {

                    register_error = 1;
                    error = jsonObjSend.getString("error");
                    if (error.equals("3")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("4")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("5")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("6")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("7")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("8")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("9")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("10")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("11")) {
                        msg = jsonObjSend.getString("message");
                    } else if (error.equals("12")) {
                        msg = jsonObjSend.getString("message");
                    } else {
                        msg = jsonObjSend.getString("message");
                    }
                    // {"status":1,"message":"There is no activity of the selected day and filtering otpions"}
                } else if (jsonObjSend.getString("status").equals("1")) {

                    if (jsonObjSend.has("message"))
                        msg = jsonObjSend.getString("message");
                    // msg = jsonObjSend.getString("message");
                    register_error = 0;
                    operation = new JSONArray();
                    if (jsonObjSend.has("list")) {
                        operation = jsonObjSend.getJSONArray("list");

                        // arraylist_oper = new ArrayList<HashMap<String,
                        // String>>();

                        for (int i = 0; i < operation.length(); i++) {
                            map = new HashMap<String, String>();
                            qr = operation.getJSONObject(i)
                                    .getString("qrcode");
                            type = operation.getJSONObject(i)
                                    .getString("type").toString();

                            Log.d("Types", type);
                            String origin = operation.getJSONObject(i)
                                    .getString("origin");
                            String destiny = operation.getJSONObject(i)
                                    .getString("destiny");
                            String stop_status = operation.getJSONObject(i)
                                    .getString("stop_status");
                            String stop_status_name = operation
                                    .getJSONObject(i).getString(
                                            "stop_status_name");
                            String stop_status_color = operation
                                    .getJSONObject(i).getString(
                                            "stop_status_color");
                            map.put("qrcode", qr);
                            map.put("type", type);
                            map.put("origin", origin);
                            map.put("destiny", destiny);
                            map.put("stop_status", stop_status);
                            map.put("stop_status_name", stop_status_name);
                            map.put("stop_status_color", stop_status_color);
                            // map.put("status_name", status_name);
                            arraylist_oper.add(map);

                            Log.d("qrcode:", qr + " type: " + type
                                    + " origine: " + origin);
                        }
                    } else {

                        msg = jsonObjSend.getString("message");
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return content;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.dismiss();

        if (error.equals("6")) {

            Intent intent=new Intent(OperationalControl.this,LoginActivity.class);
            startActivity(intent);
            OperationalControl.this.finish();

        }
        try {
            if (arraylist_oper.size() > 0) {
                Operational_LazyAdapter adpt = new Operational_LazyAdapter(
                        getApplicationContext(), arraylist_oper);
                listView1.setAdapter(adpt);
                // Toast.makeText(getApplicationContext(), msg,
                // Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "Office não definir corretamente ou" + msg,
                        Toast.LENGTH_LONG).show();

                noresponse.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Response

{"status":1,
    "list":[{
        "qrcode":"#00000757-00000277-700101-0000000040",
        "type":"Tipo de Opera\u00e7\u00e3o: Chegada",
        "origin":"Origem: ARMAMAR (757)",
        "destiny":"Destino: REGUA (277)",
        "stop_status":6,
        "stop_status_name":"Finalizado",
        "stop_status_color":"#cccccc"
    },
    {
        "qrcode":"#00000278-00000277-700101-0000000041",
        "type":"Tipo de Opera\u00e7\u00e3o: Chegada",
        "origin":"Origem: LAMEGO (278)",
        "destiny":"Destino: REGUA (277)",
        "stop_status":6,
        "stop_status_name":"Finalizado",
        "stop_status_color":"#cccccc"
    }]
}

Button text size is presented differently in two different fragments on S5 with android 5.0

I'm using same adapter, same list item layout for the lists in two different fragments but somehow textSize of a button is larger in one of them even if I have defined size in xml.

I have to mention that there is no difference in button text size when I test on S3 for instance which is android 4.3.

Normal size

Magnified size

Layout:

<Button
    android:id="@+id/bFollow"
    style="?android:attr/borderlessButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="32dp"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="4dp"
    android:background="@drawable/ib_follow"
    android:contentDescription="@string/cd_follow"
    android:focusable="false"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:textColor="@color/m_orange"
    android:textSize="12sp" />

Can someone offer any explanation on this?

How to install my NativeScript application in my phone?

I have build an android application using NativeScript but now i want to install it in my android phone but i don't know which .apk file i have to take to install the application in my phone.

Thanks for answering.

Use ApplicationContext if possible in Android?

Is it a good practice to use application context instead of other context(Activity, Service and so on) if possible? Pros:

  1. Application context can help us avoid memory leak.
  2. Application context can help eliminate params in some circumstances
  3. Other things don't come to my head for now

Cons:

No clue for me after googling for a while and this is where this question from.

APK file creation in Android Studio

I tried creating an apk file in android studio, On assembling the module and then running it isn't creating any output file in the build. Only 2 folders are there in build intermediates and generated.. Any help is appreciated..

Android: Facebook like button doesn't work

I'm trying to integrate facebook "like" button into my Android app. I'm using Facebook SDK 4.1.2.

My app has the Main Activity with Navigation Drawer, which switches the Fragments. One of the Fragments has the ListView. I need facebook "like" button in every list item. I'm using custom BaseAdapter to construct the list items.

I don't have problems with the facebook signing in and with getting posts from some facebook page.

But I faced with the next problems:

  1. The "Like" button doesn't have any likes count, it just looks like this

1

By the way, is it possible to make this button looks like this?

2

  1. My "like" actions doesn't make any effect. I press the "like" button, some screen appears and fastly closes, and then I can't see any changes with the button, and the Facebook object (some page post) doesn't get my like (I check it via browser).

What am I missing with this task?

Here's parts of my code:

MainActivity.java

private CallbackManager callbackManager;

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

    FacebookSdk.sdkInitialize(getApplicationContext());

    callbackManager = CallbackManager.Factory.create();

    OpenFacebookSession();

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}

ListAdapter.java

public class ListAdapter extends BaseAdapter {  

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.feed_item, null);

        LikeView likeView = (LikeView) convertView.findViewById(R.id.like_view);
        likeView.setLikeViewStyle(LikeView.Style.BOX_COUNT);
        likeView.setAuxiliaryViewPosition(LikeView.
            AuxiliaryViewPosition.INLINE);

        likeView.setObjectIdAndType(someID,//some Facebook object ID
                                    activity-launchmode/en",
                                    LikeView.ObjectType.OPEN_GRAPH);
        return convertView;

    }


}

feed_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/feed_bg"
    android:orientation="vertical" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="@dimen/feed_item_margin"
    android:layout_marginRight="@dimen/feed_item_margin"
    android:layout_marginTop="@dimen/feed_item_margin"
    android:background="@drawable/bg_parent_rounded_corner"
    android:orientation="vertical"
    android:paddingBottom="@dimen/feed_item_padding_top_bottom"
    android:paddingTop="@dimen/feed_item_padding_top_bottom" >

    <com.facebook.share.widget.LikeView
        android:id="@+id/like_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/feedImage1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    </RelativeLayout>

</LinearLayout>

Android, how to use the Accelerometer Sensors?

can someone help me understand the Accelerometer Sensor. I've read this and this overviews about the sensors and the motion sensor but i can't understand which movement triggers which sensor, (for an example the Sensor TYPE_ACCELEROMETER and Sensor event data SensorEvent.values[0] means Acceleration force along the x axis (including gravity).) what does that mean? which motion is it? So if anyone can help me, please all I want to know is to check if the phone is on a landscape orientation and standing vertically, and when the phone gets tilted to the front or backward. these are the 3 movements that I want to know, thanks

android weird memory issue with my app

I'm new to Android. My app's memory usage increased 10 MB when I add
<ImageView android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/icon"/> to my main activity's xml file. the drawable is a 64x64 png icon which only takes 4kb space on my hard drive. it seems all other icons in my app are using 100-1000 times of their actual sizes in memory. Why is that and How can I solve this? I'm using Nexus 5 emulator with api level 17

Login button facebook android doesn't redirect to new activity

When i run my Android app, and click approve to the give permissions it not get redirected to the MainActivity. The "Logged in" message doesn't shows up in the Catlog. I have read the Facebook developers guide, and compared my code to different topics here at Stack. I can't see i have done anything wrong.

I would be very glad for help.

public class Login extends Activity {

/**
 * Called when the activity is first created.
 */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);
    final CallbackManager callbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile", "email", "user_friends");


    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }



        @Override
        public void onSuccess(LoginResult loginResult) {

            Intent i = new Intent(Login.this, MainActivity.class);
            startActivity(i);
            System.out.print("Logged in");

        }

        @Override
        public void onCancel() {
            // App code

        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.i("Error" , "Error");
            }


        });
    }
}

Your app is statically linking against a version of OpenSSL that has multiple security vulnerabilities.

I got this error in one of my live application. I am not using any OpenSSL library in my app.So,Please any one can help me with this? I am using some 3rd party Libraries like : Twitter,FB,Parse etc. May be they are creating any problem?Or may be App is signed with older keystore can be the cause? Any help is appreciable...

Also,I have got this warning 2nd time?It can be possible,my app can be rejected after 3rd warning? Please suggest.

Click ImageView on Specific Location

I have an imageView and when I need to let the user click only on a specific location (the white space) as shown in the image below, any suggestion?

enter image description here

here is my xml

    <RelativeLayout
            android:id="@+id/lockRelativeLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginStart="5dp"
            >
            <ImageView
                android:id="@+id/imageView"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@drawable/image" />
        </RelativeLayout>

and here is the code

    private View.OnTouchListener imageViewOnClickListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int x = (int)event.getX();
            int y = (int)event.getY();
            if (event.getAction() == MotionEvent.ACTION_DOWN){
               //here i want if he clicked on specific location to go to another activity
 Intent intent = new Intent(context, ViewerActivity.class);
            context.startActivity(intent);
            }
            return true;
        }
    };

I don't know if i should use onClick or onTouchClick!!

limited CheckBox in gridview

Please help me to check the coding, how to set 5 limited for checkbox selection in grid view, I am using SparseBooleanArray.....

        holder.cb.setTag(position);
        holder.cb.setContentDescription(Uri.withAppendedPath(
              MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID).toString());
        holder.cb.setChecked(mSparseBooleanArray.get(position));
        holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                mSparseBooleanArray.put((Integer) buttonView.getTag(),  isChecked);


            }
        });

How to start my application after device boot? [duplicate]

This question already has an answer here:

i want to develop an application that starts after device boot.

i use this code but it dose not worked.

i the manifest i use both android:name=".receiver.StartMyServiceAtBootReceiver" and android:name="StartMyServiceAtBootReceiver" but it dose not worked.

whats the problem ?

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="com.example.onstart"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <service android:name=".MySystemService" android:label="MySystemService">
             <intent-filter>
               <action android:name="com.example.onstart.MySystemService" />
              </intent-filter>
        </service>

        <receiver
             android:name=".receiver.StartMyServiceAtBootReceiver"
             android:enabled="true"
             android:exported="true"
             android:label="StartMyServiceAtBootReceiver">
            <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED" />
             </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            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>

StartMyServiceAtBootReceiver:

package com.example.onstart;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, MySystemService.class);
            context.startService(serviceIntent);
            Toast.makeText(context, "On Receive 1", Toast.LENGTH_LONG).show();
        }
    }
}

MySystemService:

package com.example.onstart;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MySystemService extends Service{
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
     public void onCreate() {
            super.onCreate();
     }
    @Override
    public void onStart(Intent intent, int startid)
    {
       Toast.makeText(getApplicationContext(), "On service start 1", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}

mercredi 6 mai 2015

Oracle trigger for allowing DML on view

I have View in Oracle DB:

  CREATE VIEW view1
AS SELECT
  id, c1, c2, c3, c4, c5, c6
FROM
  table1
WHERE
  c1>1100 AND c1<2000
WITH CHECK OPTION;

And table table1 with columns id, c1, ... c9. Now i want make trigger(s) on this view for allowing DML operations with data thas is not in this view. But i dont know whitch columns will be updated, whitch rows deleted or inserted. For example

UPDATE view1 SET c1=3000 WHERE c1=1500;

or

INSERT INTO view1 VALUES(3500, .......);

Someone has an idea?

Edit: I know, that doesn't make sense, but this is part of my project and this part will show how to bypass the constraint of view.

Way to make Product Groups in E-commerce database

I have the following scenario in my database: Simple Product-Cart database

With this structure, I can show the following information to my user:

"Your cart has 2 products, with the total of $400

  • Product 1, $100
  • Product 2, $300
  • Total: $400 ".

My company wants to sell products inside groups to give discounts to its customers. And I need to show information like this:

"You are buying Product Group 1 which has the following products:

  • Product 1, $100
  • Product 2, $300
  • Product 3, $240 .... Total: $1000".

So I've remodelled the database to something like this: Remodeled Database

But I'm facing some problems, and would like to know if this the best way to work with item grouping in an ecommerce application?

A customer can choose this package into his cart with (or without) other individual products, what kind of generalization can be used here?

I am creating a small database on SQL Plus (Oracle). How to add a user interface to it?

Like, I want it in such a way that the user who is on the front end, commands or maybe simply clicks for a particular value and the queries are happening at the back-end of the database.

Basically I was looking for some type of form or some type of a nice little G.U.I with a bit of functionality.

Oracle Connection String - What exactly the difference?

.Net Framework Connection string: "Provider=MSDAORA;Data Source= Your_Oracle_Database; UserId=Your_Username; Password=Your_Password;"

Connection string to obviate the need - tnsnames.ora

string oradb = "Data Source=(DESCRIPTION=" + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=ORASRVR)(PORT=1521)))" + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));" + "User Id=scott;Password=tiger;";

What is best practice when preparing insert statement for re-use within class?

I'm using PHP at the moment, but the question is just as valid for other languages I believe.

I have a class OfferProduct that represents a product within an offer. One offer can contain multiple products. This class has a function save() that prepares statement and executes it.

To avoid preparing a statement that already exist I added a private static variable to the class $isPreparedStatementDeclared. If isPreparedStatementDeclared is false the statement will be prepared, which happens the first time save() is called.

public function save() {
    global $db;

    if (!self::$isPreparedStatementDeclared) {
        $db->prepare('new_offer_product', 'INSERT INTO offer_product (' .
                'product_id, ' .
                'price_ex_vat, ' .
                'vat_percent, ' .
                'amount, ' .
                'discount_percent, ' .
                'free_text, ' .
                'qty_type, ' .
                'offer_id' .
                ')VALUES (' .
                '$1, ' .
                '$2, ' .
                '$3, ' .
                '$4, ' .
                '$5, ' .
                '$6, ' .
                '$7, ' .
                '$8)');

        self::$isPreparedStatementDeclared = true;
    }

    // Return bool result of query
    return ( $db->execute('new_offer_product', array(
                $this->productId,
                $this->priceExVat,
                $this->vatPercent,
                $this->amount,
                $this->discountPercent,
                $this->freeText,
                $this->qtyType,
                $this->offerId)));
}

Is this good practice?

It doesn't seem like a good solution to prepare the statement outside of this class, and then loop through every product and call save().

Maybe a separate class PreparedStatements where prepared statements are stored in a static array, and the class prepares statement if it hasn't already been prepared?

Flushing dirty pages to the data pages disc

I am confused about when to flush dirty pages to the data pages disc. As I understand T-log disc and data pages disc are different from each other and when buffer pool is full and do not have enough space least recently used page is flushed to the data pages disc. And when a transaction commits it is flushed to the T-log disc but not data pages? When to flush dirty pages to the data pages disc?
Here is the link that I read from: http://ift.tt/1EfNPQa

MySQL error from a named query

I have a simple named query . We did an upgrade of hibernate libraries and we are seeing the following error . It was working fine in previous version.

Any reason why simple query fails like this ?

    Caused by: org.hibernate.exception.GenericJDBCException: could not execute query
        at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140) [hibernate3.jar:]
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128) [hibernate3.jar:]
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) [hibernate3.jar:]
        at org.hibernate.loader.Loader.doList(Loader.java:2545) [hibernate3.jar:]
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276) [hibernate3.jar:]
        at org.hibernate.loader.Loader.list(Loader.java:2271) [hibernate3.jar:]
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:459) [hibernate3.jar:]
        at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:365) [hibernate3.jar:]
        at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) [hibernate3.jar:]
        at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268) [hibernate3.jar:]
        at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) [hibernate3.jar:]
        at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:246) [hibernate3.jar:]
        ... 157 more
Caused by: java.sql.SQLException: java.lang.IllegalArgumentException: Negative delay

CakePHP: Multiple Model in Controller Action:add

I just started with CakePHP recently. The framework make things easy, but today I just find myself a new question.

If a Project model has an image, it would be accessible somewhere like $this->data['Project']['image']. Since there's only 1 image to 1 project, it can be a field in the Project table itself.

But what about if Project has a collection of images? Wouldn't it be another table say Gallery? Then we're talking about two Model here.

For the previous case, image can easily be uploaded in project/add, storing the filename into projects.image. Things happen in Project Model, and Project Controller.

Now how's the cake way to do it when adding a Project with a Gallery?

Local database does not submit changes after insert into in Visual Studio/C#

I have this problem with Visual Studio. I have a Service Based Database - KCSDatabase.mdf and 1 table in it- Users. I use it to create a LINQ class of it by drag and drop the table in the context of my UserDataClasses.cs. I have one Stored Procedure - AddNewUser in the database and in UserDataClasses.cs too. For connection it uses the connectionString defined at App.config - My connectionString is :

onnectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\KCSDb.mdf;Integrated Security=True"

So, when I submit a form with user data from registration and debug the app the database does not update the changes after insert into. When I try to add two rows at one session with unique ids - it get me the notification that I can not insert because of the primary key (id) and does not make the changes in database. But if I do it at two separate times - two times I start the app and insert user with same id and it doesnt notify me and it does not make the changes at database too. Somebody says me that it writes somewhere the inserting information (in some file, which is destroyed after closing the app) but does not insert in in the database. This is the code of saveButtonClick event of my form:

UserDataClassesDataContext dc = new UserDataClassesDataContext();

dc.AddNewUser(Convert.ToInt32(tbId.Text),
              tbFirstName.Text,
              tbMiddleName.Text, 
              tbLastName.Text, 
              tbMail.Text, 
              tbUserName.Text, 
              tbPassword.Text);
dc.SubmitChanges();

vb.net oracle database datagridview1.datasource=rs is not working

Imports System.Data.Odbc Imports System.Data.OleDb Imports ADODB Public Class Form3

Dim str As String

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    conn = New ADODB.Connection
    rs = New ADODB.Recordset
    str = "Select * from studenttable where(dept='" & ComboBox1.SelectedItem & "' and year='" & ComboBox2.SelectedItem & "')"

    conn.Open("driver={microsoft ODBC for Oracle};uid=hr;pwd=hr;")

    rs.Open(str, conn, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockPessimistic)

    TextBox1.Text = rs.Fields.Count

    MsgBox("en1")

    Me.DataGridView1.DataSource = rs



    rs.Close()
    MsgBox("en2")
End Sub

Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    conn = New ADODB.Connection

    If (conn.State = ConnectionState.Open) Then

        conn.Close()

    End If

End Sub

End Class

datagridview1.datasource=rs is not working hjgfhjsgvhjsvhbsvzhbxc hjfgs\hdvhjsdc

Attach database file from SQL Server 2012 to Visual Studio 2013

I want to attach a dataase file (.MDF) from SQL Server 2012 to Visual Studio 2013, but after I choose "Microsoft SQL Server Database File(SqlClient)" and choose the .mdf file, this error appear:

The attempt to attach to the database failed with the following information:
A network-related or instance-specific error occurred while establishing a connection to sqlserver . The server was not found or was not accessible. Verify that the instance name is correct and that sqlserver is configure to allow remote connections.

I am confused. I installed / uninstalled times and times different versions of SQL Server 2008, 2012, 2014 but it doesn't work.

What can I do?

creating new database manually for a software every time while distributing it to a new user?

I've made a desktop based shop-management software using java that will save every product detail and sell history of a particular shop in a database over internet (phpmyadmin). I've a made a connector class and give the path of the database name which connects to the database. The problem is, for every distinct shop I need to create a different database. If i make a .exe file or installation file of my software and distribute it to users, how am i going to create different databases for each user (in this case each shop) through installation process. Is there any way of doing this dynamically or I have to create the database every time before distributing it to a new user (for a new shop actually) ?

Thanks in advance I never make a software to distribute commercially. This is new to me.

'Delete' user but keep records (foreign keys)

I have a table users with user accounts (user_id, username, ...). The user_id is related to multiple other tables - e.g. a table with his last actions, profile details, his products, his interests etc.

Sometimes a user wants to be deleted, and then I set a field 'deleted' to 1. The records in most of the tables should be deleted, but the records in 2 tables (reports and messages) should keep the reference to the user. Reason: For example, a message partner still wants to see the username of the account he recently talked to. What is the best way to do this?

1) In PHP store the ids of the records in reports and messages that should be kept in an array. Then delete the user. Automatically all the tables related to users delete their records with a reference to the deleted account. The reference in reports and messages should be: ON UPDATE SET NULL so their records still exists after user delete. The database is clean now, then re-insert the user with the same user_id with the field 'deleted' to 1. Then update the data in the array to the user_id so the reference is set again.

2) Remove the references to the user in reports and messages (so there are no foreign keys).

3) ... (is there a better option?)

Thanks!

Multiple crawlers database connection in Java

Let's say I instantiate multiple crawlers for the same URL. They write URLs that are processed to MySQL database. Before processing URL, they check in database if record for that page exists, so it wouldn't process already processed page again.

Here is the catch, there should exist some kind of lock, so that only one of them can read or write from that specific table, if my logic is right. So, I instantiated only one database connection (JDBC) for them to use. Still, I am unsure if this is right thing to do.

So my question is: do statements executed from single database connection run sequentially(are they queued) or does this depend on database engine it's configuration.

Change Magento bundle product price type via database

Is it possible to change an existing bundle product from dynamic to fixed price via the database rather than having to create a new product?

PHP Code Login Failure [on hold]

I'm kinda new at working with PHP. I'm trying to make a system with a Login, a friend helped me with the codes, but an error appears when I'm trying to connect to the data base.

I'm using: * Wampserver * PostgreSQL

After logging in, I get this error:

Fatal error: Call to undefined method DBConnection::Consultar() in C:\wamp\www\Intranet\App\Controllers\validaringreso.php on line 11

And in the php code I have this:

1  <!-- validaringreso.php -->
2  <?php
3  //@session_start();
4  include($_SERVER['DOCUMENT_ROOT'] . "Intranet/App/Models/funciones.php");
5  include($_SERVER['DOCUMENT_ROOT'] . "Intranet/App/Models/conect_.php");
6  
7  $login=addslashes($_POST["usuario_emp"]);
8  $pass=addslashes($_POST["contrasena_emp"]);
9  $bd=new DBconnection();
10 $bd->sentencia="SELECT * FROM usuarios_emp WHERE usuario_emp='$login' AND contrasena_emp='$pass'";
11 $rs=$bd->Consultar();
12 if($bd->NumeroFilas($rs)>0){
13  $fila=$bd->AvanzarFila($rs);
14  $_SESSION["id"]=$fila["id"];
15  $_SESSION["usuario_emp"]=$fila["usuario_emp"];
16  $_SESSION["constrasena_emp"]=$fila["constrasena_emp"];
17  $bd->LiberarResultado($rs);
18  $bd->Cerrar();
19  header('Location: principal.php');
20 }else{
21  echo "<script language='javascript'>
22 alert('Datos Incorrectos');
23 parent.location.href = 'index.php';
24 </script>";
25 }
26 ?>

Ask localisation in a form

So let's say I have a web app where people can add places they like. My database would look like this:

+-----------+----------------+--------------+---------------+
|    Name   |     Adress     |   Latitude   |   Longitude   |
+-----------+----------------+--------------+---------------+
| Blue Cafe | 8, Blue St, NY |  70,354635   |   47,56946    |
+-----------+----------------+--------------+---------------+

I can't ask my users to enter Latitude and Longitude.

I know Google Maps API can convert an adress to latitude/longitude, but:

  • How can I ask an adress an know that it exists in Google's database?
  • Can I show a map where people would click to locate the place?

What should be stored in DB when converting site into rails [on hold]

I believe this is more of a subjective question than not, that being said, I am much newer to rails than a lot of you, so I trust your opinion more than my own. Basically I've been talking to someone I know about redoing there website into a rails app, but I am not sure how the best way to go about setting up the database would be. Here is a link to the site I will be remaking http://ift.tt/1OY6mvK.

My question to you is, what all belongs in a database? My first thought is to create two main tables in the db, sections and articles, and have each article belong to a section. I will store all of the html for the content of each separate pages in the db under a certain section (for instance the "welcome", "FAQs", "Contact Information", and all other links under the about dropdown menu will be separate articles stored in the db which belong to the "About" section.)

**Update 5/05/2015 2:37 PM CDT I should clarify that when I say I will post the html for each of those pages in the database, I do not mean ALL of the html on that given page, just the content on those pages that is unique to that page (so headers, menu bars, etc. will not be stored in the database)

However, I'm beginning to wonder if storing all that html and text in a database would be too much, or would be bad practice, and if it is better to just create separate html files for each page, too make it easier to style text and create tables within text and stuff like that. I see pros and cons to both sides, a huge pro, for example, is the fact that if I did store it in the database I would not need to create 30+ HTML files, and could just pass in different Articles from the database into a preformatted page.

So I'm just looking for some advice on what you guys think is the best way to go about this project!

WordPress Custom Database if statement and Update issues

I'm trying to update a custom database called wp_afterhours. Here is a look at what it holds. database snapshot

Is there a better way where I can use two option dropdowns, so the user can select one of three options for the primary contact, and one of three options of the secondary contact (with an if statement to compare the selections, to make sure the same isn't chosen for both). I want to be able to compare using php and to update the database with the primary_tech field set to one, for the primary, and the secondary_tech field set to 1 for the secondary. Of course, if there is a previous selection, it would need to be put to zero, as well. I have been trying this for a while now and have had no luck. Can someone help me find a decent solution? The comparison doesn't work at all, at this point. //update query $wpdb->query( " UPDATE $wpdb->wp_afterhours SET primary_tech = 1 WHERE id = $primary_selection; " ); $wpdb->query("UPDATE $wpdb->wp_afterhours SET secondary_tech = 1")

and this for the if statement `if the form is submitted if (isset($_POST['submit'])) {

//check to make sure both options chosen are not the same
if ($_POST['primary_'] === $_POST['secondary']) {
    $hasError = true;
    $hasErrorMessage = "Both Options cannot be the same.  Change one.";
} else {
    $hasError = false;
    $primary_contact = $_POST['primary_contact'];
    $secondary_contact = $_POST['secondary_contact'];
}

// retrieve the primary tech info

} `Please help!

How to create a Access App from a .accdb?

I'm trying to create a .app from a .accdb file but Access 2013 don't show me the option in Save as.

Anyone knows what I can do?

Thanks in advantage

Best remote database for Android app

I am developing a android application for my family members just like a social networking site.But i don't know any proper database to be used as remote back end.Also I need a database which serves the post's based on timestamps.Also my database should be flexible of inserting any type of files(txt,png,PDF etc...) for downloading by the user's.Suggest a goodbase One more thing I recently used MongoDB an I am fed up using the java driver for the accessing of data in Mongo DB.Is MongoDB also a good option of selecting asa remote database.Also suggest me the links for installation also.

PHP :: Storing a database connection v. static instantiation

Which of these approaches is more efficient (or proficient) in PHP?

class Amazing {
    protected $db;

    public function __construct () {
         $this->db = new Database::getInstance();
    }

    public function do ($blah) {
         $this->db->doInsert($blah);
    }

    public function again ($blah) {
         $this->db->doUpdate($blah);
    }
}

OR:

class Less_Amazing {

    public function do ($blah) {
         $db = new Database::getInstance();
         $db->doInsert($blah)
    }

    public function again ($blah) {
         $db = new Database::getInstance();
         $db->doUpdate($blah)
    }
}

A pint of beer is riding on the answer.

How to intercept and change data passing from DB to ListView?

In my application I read data from database, put it into cursor and pass it to ListView using adapter. These data are numbers from 1 to 12, but I need them to be presented in the ListView as names of months. How and on which step of reading and displaying these data can I intercept them and change from numbers to text?

ArgumentError: no time information in "0" using ActiveRestClient in rails 4.2.1

I'm trying to use an API as a database for my rails application using ActiveRestClient, but when I try to query from the API I get an ArgumentError: no time information in "0". I don't understand where the call to time.rb is coming from. Any ideas what causes the problem and how I can solve this problem?

Thanks in advance!

This is the code I'm using:

class Db < ActiveRestClient::Base
  base_url "https://Placeholder/api/vtest/"
  get :all, "/customer?apiKey=tester"
  get :find, "/customer/:id?apiKey=tester"

  before_request do |name, request|
    request.headers["Accept"] = "application/json"
    request.headers["User-Agent"] = "random"
  end
end

And this is the error message I'm getting:

ArgumentError: no time information in "0"
    from /home/wouter/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/time.rb:252:in `make_time'
    from /home/wouter/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/time.rb:364:in `parse'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/active_rest_client-1.0.8/lib/active_rest_client/caching.rb:69:in `write_cached_response'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/active_rest_client-1.0.8/lib/active_rest_client/request.rb:162:in `block in call'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/active_rest_client-1.0.8/lib/active_rest_client/request.rb:116:in `call'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/active_rest_client-1.0.8/lib/active_rest_client/mapping.rb:46:in `_call'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/active_rest_client-1.0.8/lib/active_rest_client/mapping.rb:28:in `block in _map_call'
    from (irb):1
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/railties-4.2.1/lib/rails/commands/console.rb:110:in `start'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/railties-4.2.1/lib/rails/commands/console.rb:9:in `start'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/railties-4.2.1/lib/rails/commands.rb:17:in `<top (required)>'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `require'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `block in require'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `require'
    from /home/wouter/projects/NavAds/Test/bin/rails:8:in `<top (required)>'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `load'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `block in load'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /home/wouter/.rvm/gems/ruby-2.2.2@global/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:268:in `load'
    from /home/wouter/.rvm/rubies/ruby-2.2.2/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /home/wouter/.rvm/rubies/ruby-2.2.2/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'