Sunday, 7 August 2016

Fix Error No camera with exception: Fail to connect to camera service Android Marshmallow





Hello world, today i have problem when i develop android app. For first time i see, i so  shock about it. Lol. Actually apps its really done, for Jelly Bean OS, but when i try to new Marshmallow OS i got some error. Yap this is is ' Fail to connect to camera service '. And i already set permission on manifest file, like this one. 

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" ></uses-permission>

So whats happen? After i did try to find, i got solution about this case. So marshmallow have different permission to get it. You can read on this article Android Developer . On the marshmallow os we need to set additional permission on java code too.

Before I show to create additional permission on java code, i will make you sure about this case. On my case i got problem when i show camera in my apps, and the error is 'Fail to connect to camera service' . This problem cause i not yet to set additional permission on my java code. This is happen just on marshmallow OS, so bellow marshmallow os we don't need to set this. Note that.

This is my java code to set additional permission.

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 111: {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("Permissions --> " + "Permission Granted: " + permissions[i]);


                } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    System.out.println("Permissions --> " + "Permission Denied: " + permissions[i]);

                }
            }
        }
}

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        int hasCameraPermission = getActivity().checkSelfPermission(Manifest.permission.CAMERA);
        int hasWritePermission = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        List<String> permissions = new ArrayList<String>();

        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.CAMERA);

        }
        if (!permissions.isEmpty()) {
            requestPermissions(permissions.toArray(new String[permissions.size()]), 111);
        }
    }
}

So on this code i have conclusion like this :

1. On function onStart() it will show pop up to set our application for first time activity run. If users agree about our permission, application will got permission. Ass you can see, permission will be save on variable list permission permissions.add(Manifest.permission.CAMERA); . 

2. On the function onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) it will show message we get permission on apps or not. If our application get permission, it will move on this condition : 

 (grantResults[i] == PackageManager.PERMISSION_GRANTED)

and if else will be move on this condition

(grantResults[i] == PackageManager.PERMISSION_DENIED)

Just it, i hope this is can help you, if you have same problem like me. You can try this way, i hope we can learn together for develop beautiful android apps. And last i wanna say, don't forget to comment bellow if you have confuse about my code. Thanks. 
Share:

Tuesday, 26 July 2016

How to get Data from JSON Show on List Android



https://dedyyuristiawan.blogspot.com

Hello world, today I am gonna share about get data from the JSON. In this case I will use volley library for make easy develop, when i get data from JSON. Actually this is test for myself, to remain me about android code. And this is my list :

1. A Activity have one button, two edit text.
2. When your click button will move to another activity, I call it Activity B, Activity B will show list data from JSON.
3. When you click your list, it will will be back to Activity B with fill two EditText.
4. Just it.

Hoya, in this tutorial i use JSON from androidhive. You can check here. He share about JSON too but in this post i will make it complete :D.

Now you follow my step by step :

1. Activity A 

In this Activity A I just put One Button and with Two EditText this is my activity_main.xml file :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btnArrayRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:text="Pick Doctor" />

    <EditText
        android:id="@+id/ETCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:layout_below="@id/btnArrayRequest"
        />

    <EditText
        android:id="@+id/ETName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:layout_below="@id/ETCode"
        />

</RelativeLayout>

and this is my MainActivity.java file :


public class MainActivity extends Activity {
 
 private static String TAG = MainActivity.class.getSimpleName();
 private Button btnMakeArrayRequest;
 private EditText ETCOde;
 private EditText ETName;

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

  btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
  ETCOde = (EditText)findViewById(R.id.ETCode);
  ETCOde.setEnabled(false);
  ETName = (EditText)findViewById(R.id.ETName);
  ETName.setEnabled(false);
  btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this,
MainActivityList.class);
    startActivity(intent);
   }
  });
  if (getIntent() != null){
   if (getIntent().hasExtra("Code")) {
    ETCOde.setText(getIntent().getStringExtra("Code"),                                 TextView.BufferType.EDITABLE);
   }
   if (getIntent().hasExtra("Name")) {
    ETName.setText(getIntent().getStringExtra("Name"),                                 TextView.BufferType.EDITABLE);
   }
  }
 }
}

See on my first list, function button its for move to Activity B. You can see on this code :

btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      Intent intent = new Intent(MainActivity.this,
                        MainActivityList.class);
      startActivity(intent);
   }
});

And then as you can see in the third my list it must fill data from list Activity B.  I just use this code:

if (getIntent() != null){
    if (getIntent().hasExtra("Code")) {
      ETCOde.setText(getIntent().getStringExtra("Code"), 
      TextView.BufferType.EDITABLE);   
    }
    if (getIntent().hasExtra("Name")) {
      ETName.setText(getIntent().getStringExtra("Name"), 
      TextView.BufferType.EDITABLE);   
    }
}

This condition for detection if this activity get intent for another activity.

2. Activity B

Remember in this activity it's our main point. We will show data from JSON and will be show on list activity. So this is my activity_main_list.xml and list_item.xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list"
     />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="wrap_content"
     android:layout_height="50dp"
     android:id="@+id/name"
     android:layout_alignParentStart="true"
  android:gravity="center_vertical"  
        android:paddingStart="10dp"
 />
    
    <TextView 
  android:layout_width="wrap_content"
  android:layout_height="50dp"
     android:id="@+id/code"
  android:gravity="center_vertical"  
     android:layout_alignParentEnd="true"
        android:paddingEnd="10dp"
    />

</RelativeLayout>

In this xml file list we need to add item list for set list in xml file list. I mean element list have item list.

So this is my MainActivityList.java file in Activity B


public class MainActivityList extends Activity{

   public ListView list;    
   public ArrayList doc = new ArrayList();    
   public ListAdapter adapter;
   private String urlJsonArry = "http://192.168.88.10/api/medikav1/specialization";   private static String TAG = MainActivity.class.getSimpleName();
      
   @Override   
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);      
      setContentView(R.layout.activity_main_list);      
      makeJsonArrayRequest();
      list = (ListView) findViewById(R.id.list);
      adapter = new ListAdapter(this);
      list.setAdapter(adapter);
      list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        
   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {
      Intent intent = new Intent(MainActivityList.this, MainActivity.class);             intent.putExtra("Code", doc.get(position).name);
      intent.putExtra("Name", doc.get(position).code);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
                      Intent.FLAG_ACTIVITY_CLEAR_TASK);
      startActivity(intent);
      }
      });
   }

   private void makeJsonArrayRequest() {

      JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
            new Response.Listener() {
               @Override               
               public void onResponse(JSONArray response) {
                  Log.d(TAG, response.toString());
                  try {
                     for (int i = 0; i < response.length(); i++) {
                        JSONObject person = (JSONObject) response.get(i);
                        Model add=new Model();
                        add.name = person.getString("SpecializationID");                                   add.code = person.getString("SpecializationName");                                 doc.add(add);
                     }
                  } catch (JSONException e) {
                     e.printStackTrace();
                     Toast.makeText(getApplicationContext(),                                                           "Error: " + e.getMessage(),                                                        Toast.LENGTH_LONG).show();
                  }
               }
            }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                  error.getMessage(), Toast.LENGTH_SHORT).show();
         }
      });
      AppController.getInstance().addToRequestQueue(req);   }

}

The point of this activity is i create function for get data from Json. This is my function.


private void makeJsonArrayRequest() {

   JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
         new Response.Listener() {
            @Override               
            public void onResponse(JSONArray response) {
               Log.d(TAG, response.toString());
               try {
                  for (int i = 0; i < response.length(); i++) {
                     JSONObject person = (JSONObject) response.get(i);
                     Model add=new Model();
                     add.name = person.getString("SpecializationID");                                   add.code = person.getString("SpecializationName");                                 doc.add(add);
                  }
               } catch (JSONException e) {
                  e.printStackTrace();
                  Toast.makeText(getApplicationContext(),                                                           "Error: " + e.getMessage(),                                                        Toast.LENGTH_LONG).show();
               }
            }
         }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
         VolleyLog.d(TAG, "Error: " + error.getMessage());
         Toast.makeText(getApplicationContext(),
               error.getMessage(), Toast.LENGTH_SHORT).show();
      }
   });
   AppController.getInstance().addToRequestQueue(req);   
}

As you can see I use volley for get data Json with parameter urlJsonArry.


   JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener()
   String urlJsonArry   = "http://api.androidhive.info/volley/person_array.json"

.As i told you before, i use JSON data from android hive, you can check here. You can goto link JSON, If you want see, it would be like this.


[
 {
 "name" : "Ravi Tamada", 
 "email" : "ravi8x@gmail.com",
 "phone" : {
  "home" : "08947 000000",
  "mobile" : "9999999999"
 }
 },
 {
 "name" : "Tommy", 
 "email" : "tommy@gmail.com",
 "phone" : {
  "home" : "08946 000000",
  "mobile" : "0000000000"
 }
 }
]

You can see I am do looping and set data to my model class. And then I do add to array list with type data model. After that you can see when i set array list into list xml with this code. This is in my ListAdapter.java file.

public class ListAdapter extends BaseAdapter {
   
   MainActivityList main;
      
   ListAdapter(MainActivityList main)
   {
      this.main = main;
   }
   
   @Override
   public int getCount() {
      return  main.doc.size();
   }
 
   @Override
   public Object getItem(int position) {
      return null;   }
 
   @Override   public long getItemId(int position) {
      return 0;   }
   
   static class ViewHolderItem {
      TextView name;
      TextView code;
   }

   @Override   
   public View getView(int position, View convertView, ViewGroup parent){
      ViewHolderItem holder = new ViewHolderItem();

      if (convertView == null) {
          LayoutInflater inflater = (LayoutInflater) 
          main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_item, null);                          holder.name = (TextView) convertView.findViewById(R.id.name);           
            holder.code = (TextView) convertView.findViewById(R.id.code);                      convertView.setTag(holder);
      }
      else
      {
          holder = (ViewHolderItem) convertView.getTag();
      }
      
      holder.name.setText(this.main.doc.get(position).name);
      holder.code.setText(this.main.doc.get(position).code);
 
   return convertView;
  }
}

after adapter have value, this adapter will be add to list :


adapter = new ListAdapter(this);
list.setAdapter(adapter);

And the last remember my third list. List will move back to activity A, with fill 2 EditText. I just use this code.


list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {
 Intent intent = new Intent(MainActivityList.this, MainActivity.class);
 intent.putExtra("Code", doc.get(position).name);
 intent.putExtra("Name", doc.get(position).code);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
                        Intent.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(intent);
 }
});

As you can see, I just use intent and bring data from array list with position. Then with the array list type data model I just add .name or .code it's a getter from model class. Uha

The conclusion is if you have text like this, you can make plan one by one. Like my plan is button click, get data Json, set data Json to list, and onclick list. Hoya you can also download to my GitHub repository with click link below.

GitHub
Share:

Sunday, 26 June 2016

Make Splash Screen with Animation Android Application


https://dedyyuristiawan.blogspot.com


Hello world. Today i wanna show how to create slash screen with animation in android apps. In this post i am use small to big to small animation, you can see in demo apps. I am using last android studio and lollipop minimum sdk. lest do this.

First important thing if you want to make splash screen is logo, this is important for you and make your logo to png file, cause it can be our android apps runs fast. Splash screen its a activity so we make first activity for splash screen. This is important code in screen activity.

new Handler().postDelayed(new Runnable() {
 @Override
    public void run() {
        Intent i = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(i);
        finish();
    }
}, SPLASH_TIME_OUT);

So the purpose for this function is before we move to another activity (main activity class), the screen activity will hold until splash_time_out done. splash_time_out is integer variable. In this case i set 3000 it mean 3 second. Yup its purpose we make hander in splash screen activity.

Whats about xml layout? in xml layout i just put image and text, and image and text i will make animation. Actually this layout is similar with another layout, you can see in the my demo code.

The second thing i wanna make animation in the splash screen. So this is my important code in splash screen activity.

protected void onResume() {
    super.onResume();
    logo_holder.startAnimation(anim_logo);
    Handler handler = new Handler();
 Runnable startMain = new Runnable() {
  @Override
  public void run() {
   if (!isFinishing()){
    text_holder.startAnimation(anim_txt);
   }
  }
 };
 handler.postDelayed(startMain, 200);    
}

 The purpose onResume function is make logo_holder to start animation (anim_logo is code xml i put in the anim folder on res) and then after image done for the animation, text will be show after image done, see in condition (if finishing). 

You can download my source code bellow, after this you can see my code and understand it, if you still confuse about code, you can write comment bellow. Thanks.

Source Code Github
Share:


<br>


Advice for contacting me at dedyy54@gmail.com