I am trying to implement something similar to Apple maps' search bar that is within a child view controller like so:

enter image description here

As you can see the UISearchController is in active mode in the picture above. Once the user grabs onto the search bar and starts panning, the search controller's active mode is change to inactive and the Cancel button hides and the whole child view controller starts to move in the pan's Y direction.

Similarly, I have created the exact same UI and added a pan gesture recognizer to the search bar; however, the only state that is recognized within the life cycle of my gesture is the .began and .cancelled state of my gestureRecognizer.state. Therefore, the child view controller does not pan at all because the gesture recognizer is cancelled.

  func didPanOnSearchBar(_ gestureRecognizer: UIPanGestureRecognizer){

        switch gestureRecognizer.state {
        case .began:
            print("*** Began.")
            if searchController.isActive {
                searchController.searchBar.resignFirstResponder()
                searchController.isActive = false
            }
            break
        case .changed:
            print("*** Changed!")
            if let parentController = self.parent{
                let parentNearByViewController = parentController as! NearByViewController
                let translation = gestureRecognizer.translation(in: parentNearByViewController.view)
                self.view.center.y = view.center.y + translation.y
                gestureRecognizer.setTranslation(CGPoint.zero, in: parentNearByViewController.view)
            }
            break
        case .ended:
            print("*** Ended!")
            break
        case .cancelled:
            print("*** Cancelled!")
            break
        case .failed:
            print("*** Failed!")
            break
        case .possible:
            print("*** Possible!")
            break
        }
    }

I am assuming this line of code: searchController.isActive = false is causing the gesture recognizer to get cancelled.

My question is is there a way to change the searchController.isActive property to false and not have the gesture recognizer cancelled?

P.S.

I need to changes the searchController active mode to inactive before panning begins because the searchBar will not move with the rest of the child view controller if the searchController in in active mode.

I am building an iOS iPad app for one user. The app communicates with an PHP backend to handle the HTTP requests. How do I make sure that its the iPad app sending the HTTP requests and not an anonymous request?

Do I need to pass something through the header of HTTP request or do I need to build a tokening service using OAuth?

Bit confusing as there will only be one user off the app.

Hi i am trying to create Magento site in my android app i have to set the Login and Registration in android for customer i am trying some codes but is which way is simple and non complex for my app using PHP or directly connecting with Magento..

I have now trying Directly Connecting with Magento this is the coding:

public class Registration_Activity extends Activity implements View.OnClickListener
{
    MyTextView click;
    HttpTransportSE androidHttpTransport;
    SoapObject request ;
    SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
    private static final String NAMESPACE = "urn:Magento";
    // private static final String URL =
    // "website/api/v2_soap/?wsdl";
    private static final String URL = "http://alagendransupermart.com/index.php/rest/V1/customers";
    private static final String SOAP_ACTION = "urn:Mage_Api_Model_Server_V2_HandlerAction";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);


        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        click=(MyTextView)findViewById(R.id.signin1);
        click.setOnClickListener(this);

    }

//    @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 void onClick(View v) {
        String email = "abc@g.com";
        String firstname= "name";
        String lastname= "surname";
        String password= "password";
        CreateNewCustomer(email, firstname, lastname, password);

    }

    public void CreateNewCustomer(String email, String firstname, String lastname, String password) {


        try {
            env.dotNet = false;
            env.xsd = SoapSerializationEnvelope.XSD;
            env.enc = SoapSerializationEnvelope.ENC;
            request = new SoapObject(NAMESPACE, "login");
            request.addProperty("username", "abcd");
            request.addProperty("apiKey", "abcd");
            env.setOutputSoapObject(request);

            androidHttpTransport = new HttpTransportSE(URL);
            androidHttpTransport.call("", env);
            Object session = env.getResponse();
            String sessionId = session.toString();

            Log.d("sessionId", sessionId.toString());

            Log.d("Create "," Creating......");
            request = new SoapObject(NAMESPACE,"customer.create");
            request.addProperty("sessionId", sessionId);
            request.addProperty("product", 2080);

            //-----use Kvm Serializable class to serialize the key value data-------

            CreateCustomerKVMserialize createcustomerkvm = new CreateCustomerKVMserialize();

            createcustomerkvm.Email = email;
            createcustomerkvm.Firstname = firstname;
            createcustomerkvm.Lastname = lastname;
            createcustomerkvm.Password = password;

            PropertyInfo pi = new PropertyInfo();
            pi.setName("customerData".toString());
            pi.setValue(createcustomerkvm);
            pi.setType(createcustomerkvm.getClass());
            request.addProperty(pi);

            env.setOutputSoapObject(request);
            env.addMapping(NAMESPACE, "customerData",new CreateCustomerKVMserialize().getClass());

            androidHttpTransport.call("", env);
            Object customer_create = env.getResponse();
            Log.d("mainactivity "," "+customer_create.toString());


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

this coding shows cannot resolve

pi.setName("customerData".toString());
            pi.setValue(createcustomerkvm);
            pi.setType(createcustomerkvm.getClass());

Is there any corrections please indicate me or otherwise is there any tutorial over php for Magento is there is also welcome

Thanks in advance..

I am new to app development and I have been struggling for more than a week with no progress. I am trying to build a mobile app (ios/android) that is as simple as containing a list of 360 videos playable upon selection. I have a good sample of what I am trying to build provided by New York Times.

I was not sure if
1. Do I need to upload my 360 videos on Youtube and call them somehow (a REST API?
2. Or use Firebase to store the videos and call them (again, using a REST API?).
3. Is there a tutorial or sample works that is related to the project? Even though an app that has a list of videos and plays it when selected sounds really simple, I could not find a good work sample or tutorial for this.

Thank you in advance!

I am currently working on my Final year Project which is in android. I am using map API. I want to add a new place on my current location but i am facing this exception.

Exception SS

Exception Code SS On Selected Line

I'm using CMake to build my application and CUnit to test it. And I was wondering if there is a way to avoid including the production source files directly from the test code by name (#include ../src/foo.c strikes me as awfully ad-hoc).

I have heard of collecting the production code into a library and adding it to the CMake project, and then linking that against your production and test code. But this approach doesn't sit well with me because it makes my CMake setup that much less straightforward. So I was wondering if there is A Better Way™

I'm relatively new to Android and I'm working on a project that draws Abelian Sandpiles (a 2D Cellular Automaton). I have a grid of cells which update frequently, but at each step, it is only a small number (less than 5%) that update. Redrawing the entire grid at each steps works fine when the grid is small, but predictably slows down when the grid is large.

Based on the code from this SO post (Android: How to get a custom view to redraw partially?), I thought I could initially draw the complete grid, then cache it as a bitmap. At each step, I would then paint over the cells that need updating, cache the result, and so on.

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (needsCompleteRedraw) {
            this.cachedBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            cacheCanvas = new Canvas(this.cachedBitmap);
            doInitialDrawing(cacheCanvas);
            canvas.drawBitmap(this.cachedBitmap, 0, 0, null);
            needsCompleteRedraw = false;
        } else {
            canvas.drawBitmap(this.cachedBitmap, 0, 0, null);
            doPartialRedraws(cacheCanvas);

        }
    }

    private void doInitialDrawing(Canvas clean) {
        for (int i = 0; i < pile.gridHeight; i++) {
            for (int j = 0; j < pile.gridWidth; j++) {
                int state = pile.getGridValueAtPoint(new Point(j,i));
                clean.drawCircle(j * cellSize + cellRad, i * cellSize + cellRad, cellRad, cp.paints[state]);
            }
        }
    }

    private void doPartialRedraws(Canvas cached) {
        for (Point p : pile.needsUpdateSet) {
            int state = pile.getGridValueAtPoint(p);
            cached.drawCircle(p.x * cellSize + cellRad, p.y * cellSize + cellRad, cellRad, cp.paints[state]);
        }
    }

This works, but after a few hundred steps, it creeps to a snail's pace (regardless of the grid size). Completely redrawing at each step is significantly faster, regardless of the size. Why does this slow down so dramatically? Is there a better approach for painting over a subset of a custom view?

I am getting problem of sharing plain text on Facebook via APP. One of the method of Facebook SDK 'contentDescription' is deprecated after july,2017. Now, what method should i use for sharing content.

I am trying to implement drag and drop sorting feature in gridlayout of recyclerview using this library.I have used below code.My recyclerview is loaded perfectly with images but i am not able to drag and drop items.

Actvity

private void init()
    {
        mRecyclerView=(RecyclerView) findViewById(R.id.recycler_view);

        mLayoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);

        // drag & drop manager
        mRecyclerViewDragDropManager = new RecyclerViewDragDropManager();
        mRecyclerViewDragDropManager.setDraggingItemShadowDrawable(
                (NinePatchDrawable) ContextCompat.getDrawable(this, R.drawable.material_shadow_z3));
        // Start dragging after long press
        mRecyclerViewDragDropManager.setInitiateOnLongPress(true);
        mRecyclerViewDragDropManager.setInitiateOnMove(false);
        mRecyclerViewDragDropManager.setLongPressTimeout(750);

        // setup dragging item effects (NOTE: DraggableItemAnimator is required)
        mRecyclerViewDragDropManager.setDragStartItemAnimationDuration(250);
        mRecyclerViewDragDropManager.setDraggingItemAlpha(0.8f);
        mRecyclerViewDragDropManager.setDraggingItemScale(1.3f);
        mRecyclerViewDragDropManager.setDraggingItemRotation(15.0f);

        //adapter
        mAdapter = new DraggableGridAdapter(this,imageLoader);
//        /mAdapter = myItemAdapter;

        mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mAdapter);      // wrap for dragging

        GeneralItemAnimator animator = new DraggableItemAnimator(); // DraggableItemAnimator is required to make item animations properly.

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mWrappedAdapter);  // requires *wrapped* adapter
        mRecyclerView.setItemAnimator(animator);

        // additional decorations
        //noinspection StatementWithEmptyBody
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
            // Lollipop or later has native drop shadow feature. ItemShadowDecorator is not required.
        } else {
            mRecyclerView.addItemDecoration(new ItemShadowDecorator((NinePatchDrawable) ContextCompat.getDrawable(this, R.drawable.material_shadow_z1)));
        }

        mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView);
    }

Adapter

public class DraggableGridAdapter
        extends RecyclerView.Adapter<DraggableGridAdapter.MyViewHolder>
        implements DraggableItemAdapter<DraggableGridAdapter.MyViewHolder> {
    private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
    private Context mContext;
    ImageLoader imageLoader;

    public DraggableGridAdapter(Context c, ImageLoader imageLoader) {

        mContext = c;
        this.imageLoader = imageLoader;
        setHasStableIds(true);
        // clearCache();
    }


    @Override
    public DraggableGridAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        final View v = inflater.inflate(R.layout.item_gallery, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final DraggableGridAdapter.MyViewHolder holder, int position) {
        imageLoader.displayImage("file://" + data.get(position).sdcardPath,
                holder.ivPhoto, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        holder.ivPhoto
                                .setImageResource(R.drawable.no_media);
                        super.onLoadingStarted(imageUri, view);
                    }
                });

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public boolean onCheckCanStartDrag(MyViewHolder holder, int position, int x, int y) {
        return true;
    }

    @Override
    public ItemDraggableRange onGetItemDraggableRange(MyViewHolder holder, int position) {
        return null;
    }

    @Override
    public void onMoveItem(int fromPosition, int toPosition) {

    }

    @Override
    public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
        return true;
    }

    public static class MyViewHolder extends AbstractDraggableItemViewHolder {
        public ImageView ivPhoto;

        public MyViewHolder(View v) {
            super(v);
            ivPhoto = (ImageView) v.findViewById(R.id.ivPhoto);
        }
    }

    public void addAll(ArrayList<CustomGallery> files) {

        try {
            this.data.clear();
            this.data.addAll(files);

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

        notifyDataSetChanged();
    }

}

Adapter item xml

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="56dp">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <ImageView
        android:id="@+id/ivPhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
      />
        </FrameLayout>
    </FrameLayout>

While trying to integrate latest Dagger 2 version, I am facing problem of Dagger auto generation. Dagger is not auto generating DaggerAppComponent in spite of several Rebuilds and Make Module App process.

Application class:

public class BaseApplication extends Application
{
    private AppComponent appComponent;

    @Override
    public void onCreate()
    {
        super.onCreate();
        initAppComponent();
    }

    private void initAppComponent()
    {
        DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }

    public AppComponent getAppComponent()
    {
        return appComponent;
    }
}

AppComponent

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent
{
    void inject(BaseApplication application);
}

AppModule:

@Module
public class AppModule
{
    private BaseApplication application;

    public AppModule(BaseApplication app)
    {
        application = app;
    }

    @Provides
    @Singleton
    Context provideContext()
    {
        return application;
    }

    @Provides
    Application provideApplication()
    {
        return application;
    }
}

Dependency used:

compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.1'

Any help in this regard will be highly appreciated.

good day , i have problem withe my app , Gradle project sync failed due

Error:(22, 0) Gradle DSL method not found: 'buildConfigField()'
Possible causes:<ul><li>The project 'Weather-master' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
<a href="fixGradleElements">Upgrade plugin to version 2.3.3 and sync project</a></li><li>The project 'Weather-master' may be using a version of Gradle that does not contain the method.
<a href="open.wrapper.file">Open Gradle wrapper file</a></li><li>The build file may be missing a Gradle plugin.
<a href="apply.gradle.plugin">Apply Gradle plugin</a></li>

build.gradle

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'realm-android'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId "com.ccjeng.weather"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 10
        versionName "1.4.0.032617W"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        buildTypes.each {
            buildConfigField "String", "DARK_SKY_KEY", '"b35f87cc72b82388ed9276e41fd55dd0"'
            buildConfigField "String", "FLICKR_API_KEY", '"b35f87cc72b82388ed9276e41fd55dd0"'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'joda-time:joda-time:2.9.4'
    compile('com.mikepenz:aboutlibraries:5.8.1@aar') { transitive = true }
    compile 'com.github.bumptech.glide:glide:3.7.0'
    // compile 'com.android.support:support-v4:24.2.1'
}

am already Upgrade Gradle to v2.3.3 but its same problem ,What's wrong with the gradle-apt-plugin?

I am using google book API to search a book with the title.It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.

Here is the code I am using.

    public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Book>>{

    private static final int BOOK_ID = 1;
    public static final String LOG_TAG = MainActivity.class.getName();

    private static String book_url;

    private BookAdapter mAdapter;


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

        Button bt=(Button)findViewById(R.id.search);





        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText searchTerm=(EditText)findViewById(R.id.search_book);
                String search=searchTerm.getText().toString();

                book_url="https://www.googleapis.com/books/v1/volumes?q="+search+"&maxResults=10";

                LoaderManager loaderManager = getLoaderManager();
                loaderManager.initLoader(BOOK_ID, null, MainActivity.this);

                mAdapter=new BookAdapter(MainActivity.this,new ArrayList<Book>());
                ListView bookListView=(ListView)findViewById(R.id.list);
                mAdapter.notifyDataSetChanged();
                bookListView.setAdapter(mAdapter);


            }
        });
    }

    public Loader<List<Book>> onCreateLoader(int i,Bundle bundle){
        return new BookLoader(this,book_url);
    }

    public void onLoadFinished(Loader<List<Book>> loader,List<Book> books){
        mAdapter.clear();
        if(books!=null&&!books.isEmpty()){
            mAdapter.addAll(books);
        }
    }

    public void onLoaderReset(Loader<List<Book>> loader){
        mAdapter.clear();
    }
}

I tried notifyDataSetChanged(). But it doesn't work.

I am loading overlay sticker to my image using OpenGL ES 2.0 it is working fine in some of the devices like one plus and mi max but it is not working in some mid range devices like moto g3.

I tried other answers from stack overflow but none of them seems to work for me.

Here is my code of load

public void load(int i, int j, int k)
{
    Utils.printLog(TAG, (new StringBuilder()).append("startX:").append(j).append("  startY:").append(k).toString());
    if(bitmap != null)
    {

        GLES20.glActiveTexture(33984 + textureId);
        GLES20.glBindTexture(3553, i);

        GLES20.glTexParameteri(3553, 10241, 9729);
        GLES20.glTexParameteri(3553, 10240, 9729);
        GLES20.glTexParameterf(3553, 10242, 33071F);
        GLES20.glTexParameterf(3553, 10243, 33071F);

        imageWidth = bitmap.getWidth();
        imageHeight = bitmap.getHeight();



        Log.d("TAG", "Width is " + imageWidth + "H is " + imageHeight);
        int l;

        Log.d("TAG", bitmap.getConfig().toString());

        if(bitmap.getConfig() == Bitmap.Config.ALPHA_8)
        {
            GLES20.glPixelStorei(3317, 1);
            GLUtils.texSubImage2D(3553, 0, j, k, bitmap);
            GLES20.glPixelStorei(3317, 4);
        } else
        {
            GLUtils.texSubImage2D(3553, 0, j, k, bitmap);
        }
        l = GLES20.glGetError();
        if(l != 0)
        {
            Log.e("SubOverlay", (new StringBuilder()).append("load: texSubImage2D() ").append(l).toString());

            (new Throwable()).printStackTrace();
        }
        startX = j;
        startY = k;
        widthRatio = imageWidth / displayWidth;
        heightRatio = imageHeight / displayHeight;
        bitmap.recycle();
        initPos();
    }
}

Please help me solve this.

07-20 20:15:44.033 6471 6550 I ActivityManager: Start proc com.sec.android.inputmethod for service com.sec.android.inputmethod/.SamsungKeypad: pid=14322 uid=1000 gids={41000, 3003, 3002, 1028, 1015, 1023, 3001, 1007, 1001, 2001, 1024}

07-20 20:15:44.283 14322 14322 E AndroidRuntime: Process: com.sec.android.inputmethod, PID: 14322

07-20 20:15:44.283 14322 14322 E AndroidRuntime: at com.sec.android.inputmethod.SamsungKeypad.onCreate(SamsungKeypad.java:99)

07-20 20:15:44.283 14322 14322 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.diotek.ime.framework.common.InputManagerImpl$36" on path: DexPathList[[zip file "/data/app/com.sec.android.inputmethod-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.sec.android.inputmethod-2, /vendor/lib, /system/lib]]

07-20 20:15:46.085 6471 6934 I ActivityManager: Process com.sec.android.inputmethod (pid 14322) (adj 0) has died.(19,114)

Json File:

{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],

 "Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}

I need to display country name in first spinner and city name in second spinner as per selected countries of spinner.

How to code it android?

My Code:

public class Search_for_room extends Activity {

JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li  = new HashMap<String, String>();
public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_for_room);
    activity = this;
    ArrayList<String> items=getCountries("countriesToCities.json");
    spinner=(Spinner)findViewById(R.id.spCountry);
    spinnerCity=(Spinner)findViewById(R.id.spCity);
}

private ArrayList<String> getCountries(String fileName){
    JSONArray jsonArray=null;
    ArrayList<String> cList=new ArrayList<String>();
    try {
        InputStream is = getResources().getAssets().open(fileName);
        int size = is.available();
        byte[] data = new byte[size];
        is.read(data);
        is.close();
        String json = new String(data, "UTF-8");
        JSONObject jsonObj = new JSONObject(json);

       // JSONObject resultObject = jsonObj.getJSONObject("result");
        System.out.print("======Key: "+jsonObj);

        Iterator<String> stringIterator = jsonObj.keys();
        while(stringIterator.hasNext()) {
            key = stringIterator.next();
            value = jsonObj.getString(key);
            System.out.println("------------"+key);
            m_li.put(key,value);
            al = new ArrayList<String>(m_li.keySet());

            final SpinnerModel sched = new SpinnerModel();

            /******* Firstly take data in model object ******/
            sched.setCountryName(value);
            //   sched.setImage(key);
            sched.setStates(key);

            /******** Take Model Object in ArrayList **********/
            CustomListViewValuesArr.add(sched);
            Resources res = getResources();
            customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
            spinner.setAdapter(adapter);
        }
    }catch (JSONException ex){
        ex.printStackTrace();
        /*jsonArray=new JSONArray(json);
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jobj = jsonArray.getJSONObject(i);
                System.out.pri
                //cList.add(String.valueOf(jobj.keys()));
            }
        }*/
    }catch (IOException e){
        e.printStackTrace();
    }
    return cList;
}

}

I am new to android studio. Currently, I am trying to use Volly to fetch data from mysql. Unfortunately, the data fetch only the first ID and other information remain empty. I have tried to fetch ID only and it works, it display all the ID. However, when I fetch chapter_num and chapter_title, the output is empty. The output should have ID, chapter_num, chapter_title.

<?php

$db_name = "spmsejarahrevisionapp";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);

if (mysqli_connect_errno($conn)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$res = mysqli_query($conn, "SELECT id, chapter_num, chapter_title FROM spmtopic WHERE form='4' ORDER BY chapter_num");

$result = array();

while($row = mysqli_fetch_array($res)){
    array_push($result,
    array(
        'id'=>$row[0],
        'chapter_num'=>$row[1],
        'chapter_title'=>$row[2]
    ));
}

echo json_encode(array("result"=>$result));

mysqli_close($conn);

This is the data: {"result":[{"id":"3","chapter_num":"1","chapter_title":"Kemunculan Tamadun Awal Manusia"},{"id":"4","chapter_num":"2","chapter_title":"Peningkatan Tamadun"},{"id":"5","chapter_num":"3","chapter_title":"Tamadun Awal Asia Tenggara"},{"id":"21","chapter_num":"4","chapter_title":"Kemunculan Tamadun Islam di Makkah"},{"id":"6","chapter_num":"5","chapter_title":"Kerajaan Islam Di Madinah"},{"id":"7","chapter_num":"6","chapter_title":"Kerajaan Islam dan Sumbangannya"},{"id":"8","chapter_num":"7","chapter_title":"Islam di Asia Tenggara"},{"id":"9","chapter_num":"8","chapter_title":"Pengaruh Islam di Malaysia"},{"id":"10","chapter_num":"9","chapter_title":"Perkembangan di Eropah"},{"id":"11","chapter_num":"10","chapter_title":"Dasar British dan Kesannya Terhadap Ekonomi Negara"}]}

MainActivity.java:

public class MMapf4Activity extends CodeReuse {

public static final String JSON_URL = "http://10.0.2.2/conn.php";
public ListView listView;
private ProgressDialog loading;

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

    barRule();
    getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_arrow_left_white);

    sendRequest();

    listView = (ListView) findViewById(R.id.listView);
}

private void sendRequest(){
    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
    StringRequest stringRequest = new StringRequest(JSON_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                showJSON(response);
                loading.dismiss();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MMapf4Activity.this,error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String json){
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();
    CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.nums,ParseJSON.titles);
    listView.setAdapter(cl);
}
}

ParseJson:

public class ParseJSON {
public static String[] ids;
public static String[] nums;
public static String[] titles;

public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_NUM = "nums";
public static final String KEY_TITLE = "titles";

private JSONArray users = null;

private String json;

public ParseJSON(String json){
    this.json = json;
}

protected void parseJSON(){
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(json);
        users = jsonObject.getJSONArray(JSON_ARRAY);

        ids = new String[users.length()];
        nums = new String[users.length()];
        titles = new String[users.length()];

        for(int i=0;i < users.length();i++){
            JSONObject jo = users.getJSONObject(i);
            ids[i] = jo.getString(KEY_ID);
            nums[i] = jo.getString(KEY_NUM);
            titles[i] = jo.getString(KEY_TITLE);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

CustomList.java:

public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] nums;
private String[] titles;
private Activity context;

public CustomList(Activity context, String[] ids, String[] nums, String[] titles) {
    super(context, R.layout.spmtopic_list, ids);
    this.context = context;
    this.ids = ids;
    this.nums = nums;
    this.titles = titles;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.spmtopic_list, null, true);
    TextView textViewId = (TextView) listViewItem.findViewById(R.id.id);
    TextView textViewNum = (TextView) listViewItem.findViewById(R.id.chapter_num);
    TextView textViewTitle = (TextView) listViewItem.findViewById(R.id.chapter_title);

    textViewId.setText(ids[position]);
    textViewNum.setText(nums[position]);
    textViewTitle.setText(titles[position]);

    return listViewItem;
}
}

spmtopic.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
    android:id="@+id/id"
    android:text="New Text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/chapter_num"
    android:text="New Text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/chapter_title"
    android:text="New Text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.foong.spmsejerahscore.MMapf4Activity">

<include
    layout="@layout/app_bar_2_reuse"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/include" />

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="507dp"
    android:scrollbars="vertical"
    android:layout_below="@+id/include"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />


</RelativeLayout>

my output: Sample output

I have two activities in which I have created 4 global variable that are holding values and send them to another activity,what happening is when I clicked on button(Receive) I extract values from it and send to another activity ,values are getting stored in global variable but when I click on another button (which is also using same global variable )it'll show the previously hold value via global variable.So how can I reset my global variable at every call,though I initialized them as null.Still not getting desired output.

I'm trying to have 2 theme options for my app, Dark and Light. When the dark theme is selected I use sharedpreference to save and apply the theme on startup. But when I try to change the background color of the toolbar & appBarLayout like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    long currentTheme = sharedPref.getInt(getString(string.current_theme), 0);
    if (currentTheme == 0) {
        this.setTheme(R.style.AppTheme_NoActionBar);
    }
    if (currentTheme == 1) {
        this.setTheme(R.style.AppTheme_NoActionBar_Dark);
        Toolbar toolbar = (Toolbar) findViewById(id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setBackgroundColor(getResources().getColor(ActionbarDark));
    }

Logcat returns the error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setBackgroundColor(int)' on a null object reference

And I cant understand why

I read somewhere that you need to use a viewstub with a stylised toolbar and inflate the appropriate one on startup. But stopped the menu items from appearing when I tried.

XML File app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.papier.daniel.papier.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyActionBarTheme">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_marginTop="24dp"
        android:minHeight="?attr/actionBarSize"
        app:layout_scrollFlags="scroll|enterAlways|snap"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main"
    android:id="@+id/include"/>

</android.support.design.widget.CoordinatorLayout>

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

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzbtt.class

build.gradle

I have the following code to adopt a child view controller into a parent:

public static void AdoptViewController(this UIViewController parent, UIViewController child)
{
    parent.AddChildViewController(child);
    parent.View.AddSubview(child.View);
    child.DidMoveToParentViewController(parent);
}

This mostly works fine, except when the parent view is already visible. In such cases, the child view controller does not receive a ViewWillAppear event. This is causing knock-on problems throughout my app.

I found this post, which suggests doing this:

public static void AdoptViewController(this UIViewController parent, UIViewController child)
{
    parent.AddChildViewController(child);

    child.BeginAppearanceTransition(true, false);
    parent.View.AddSubview(child.View);
    child.EndAppearanceTransition();

    child.DidMoveToParentViewController(parent);
}

However, that causes the ViewWillAppear event to be raised twice in the case where the parent is not yet visible. I re-worked the code a bit to this:

public static void AdoptViewController(this UIViewController parent, UIViewController child)
{
    parent.AddChildViewController(child);

    // could also use ViewIfLoaded for later iOS versions
    var parentAlreadyVisible = parent.IsViewLoaded && parent.Window != null;

    if (parentAlreadyVisible)
    {
        child.BeginAppearanceTransition(true, false);
    }

    parent.View.AddSubview(child.View);

    if (parentAlreadyVisible)
    {
        child.EndAppearanceTransition();
    }

    child.DidMoveToParentViewController(parent);
}

This appears to work mostly fine, except now my ViewDidAppear event is firing twice in the child view! The first time it is triggered by EndAppearanceTransition, and the second time appears to originate from iOS itself. This isn't actually causing me any problems, but it is disconcerting nonetheless.

I'm looking for some kind of confirmation that this is the correct and idiomatic approach to adopting a child in iOS. Also, is there a sensible way to have only one ViewDidAppear call against the child?

This question already has an answer here:

I'm trying to log what I assume is an object called message, but what I get is a memory address which looks something like <Message: 0x5cy4e5db90p0>. I've mostly worked in Node so I was hoping NSLog would return something like {prop: value, prop: value} because I'm trying to figure out what properties message has. I'm also assuming message is an object because in the rest of the code, message has properties like createdOn and time.

- (void)messageUpdates:(Message*) message{ 
    NSlog(@"%@ obj", message)  
}

I deleted most of the code but essentially I want to see what is being passed into this function. Is there a way to see the properties of message instead of what I'm currently receiving? Thank you!