vendredi 29 mai 2015

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 ?