Thursday 21 November 2013

Android : Retrieve Json data from url

How to retrieve data as Json object from url in Android.
In this example when you click on the button and the system will retrieve data from url. For main Activity you can use the code from my other examples.
If there is something that is unclear, feel free to ask.







package com.example.testingdownload;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class MainFragment extends Fragment {
 
 private Button mCallButton;
 private TextView mTextView;
 private String mFetchedString;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
  View v = inflater.inflate(R.layout.fragment_main, parent, false);
  
  mTextView = (TextView) v.findViewById(R.id.view_text);
  
  mCallButton = (Button) v.findViewById(R.id.call_button);
  mCallButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    new FetchContent().execute();
   }
  });
  return v;
 }
 
 
 public void doUpdate() {
  if(getActivity() == null || mTextView == null)
   return;
  if(mFetchedString != null){
   mTextView.setText(mFetchedString);
  }
 }
 
 
 private class FetchContent extends AsyncTask {
  @Override
  protected String doInBackground(Void... params) {
   try {
    /** download data */
    return new Fetcer().retriveJsonData();
   } catch (Exception e) {
    // TODO: handle exception
   }
   return null;
  }

  @Override
  protected void onPostExecute(String result){
   mFetchedString = result;
   doUpdate();
  }
 }
}

package com.example.testingdownload;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * @author Peter Gostincar
 */

public class Fetcer {

 String url = "http://.../script_json.php (appended at the bottom)";
 private static final String JSON_ID = "id";
 private static final String JSON_NAME = "name";

 public byte[] getUrlBytes(String urlSpec) throws IOException{
  URL url = new URL(urlSpec);
  HttpURLConnection connection = (HttpURLConnection)url.openConnection();

  try {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   InputStream in = connection.getInputStream();

   if(connection.getResponseCode() != HttpURLConnection.HTTP_OK)
    return null;

   int bytesRead = 0;
   byte[] buffer = new byte[1024];
   while((bytesRead = in.read(buffer)) > 0){
    out.write(buffer, 0, bytesRead);
   }
   out.close();
   return out.toByteArray();

  } finally {
   connection.disconnect();
  }
 }

 
 public String retriveJsonData() {
  StringBuilder ret = new StringBuilder();
  try {
   String jsonString = (new String(getUrlBytes(url)));
   //Parse to json array
   JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
   for(int i = 0; i < array.length(); i++){
    JSONObject json = array.getJSONObject(i);
    ret.append(json.getString(JSON_NAME));
    ret.append(json.getInt(JSON_ID));
    ret.append(System.getProperty("line.separator"));
   }

   System.out.println();
  } catch (Exception e){
  }
  return ret.toString();
 }
}

activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />


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


    <Button
        android:id="@+id/call_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="retrieve data" />



    <TextView
        android:id="@+id/view_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="do not forget to set Manifest -Network-" />


</LinearLayout>

<?php
$arr = array(
    array(
        "id" => "1",
        "name" => "Peter"
    ),
    array(
        "id" => "2",
        "name" => "Rok"
    ),
    array(
        "id" => "3",
        "name" => "Franci"
    )
);

echo json_encode($arr);
?>

Saturday 16 November 2013

Android : Zxing onActivityResult called only in Activity - How to show it in the Fragment - tutorial


In this example I'm showing how to send data from Activity to Fragment.
With app Zxing  via Intent we read the Barcode and that we represent it in the main Fragment. The Zxing app call onActivityResult() in Activity not in Fragment.


package com.example.testingcodereading;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

public class MainActivity extends FragmentActivity {

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

    FragmentManager fm = getSupportFragmentManager();
    Fragment f = fm.findFragmentById(R.id.fragmentContainer);

    if (f == null) {
      f = MainFragment.newInstance("Start Application");
      fm.beginTransaction().add(R.id.fragmentContainer, f).commit();
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    System.out.println("the code is catch");

    IntentResult scanResult = IntentIntegrator.parseActivityResult(
        requestCode, resultCode, intent);
    // handle scan result
    if (scanResult != null) {
      FragmentManager fm = getSupportFragmentManager();

      Fragment newFrame = MainFragment.newInstance(scanResult.toString());

      fm.beginTransaction().replace(R.id.fragmentContainer, newFrame).commit();
    }

  }

}

package com.example.testingcodereading;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainFragment extends Fragment {

  private static final String EXTRA_CODE = "com.example.testingcodereading.code";
  private Button mButtonXZing;
  private TextView mTextView;

  public static MainFragment newInstance(String code) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CODE, code);

    MainFragment fragment = new MainFragment();
    fragment.setArguments(args);

    return fragment;
  }


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_main, parent, false);

    mTextView = (TextView) v.findViewById(R.id.text_code);
    mTextView.setText((String) getArguments().getSerializable(EXTRA_CODE));

    mButtonXZing = (Button) v.findViewById(R.id.button_xzing);
    mButtonXZing.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        IntentIntegrator integrator = new IntentIntegrator(getActivity());
        integrator.initiateScan();
      }
    });

    return v;
  }


  @Override 
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    System.out.println("never here");
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanResult != null) {
      // handle scan result
    }
    // else continue with any other code you need in the method
  }
}

Monday 4 November 2013

Android : Implementing long click tutorial

How to  to respond on a long click  in Android!
If you wanna the application to respond on a long click you have to implement Context Menu.
Here is an example how to create and register Context Menu.
Responding to an action is left empty to implement what needed.

I did use some code of the previous blog: Android : The scroll list. If you need the activity which started this frame go to this blog.

This is the result of the following code.





package com.mamutek.context.menu.android;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class ScrollFragment extends ListFragment{

  private ArrayList mItems;

  @Override
  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    getActivity().setTitle("Title");
    mItems = createSomeItems();

    CostumiseAdapter adapter = new CostumiseAdapter(mItems);
    setListAdapter(adapter);
  }
  
  
  /** implementing ContextMenu */
  @Override
  public void onCreateContextMenu(ContextMenu menu,  View view,
      ContextMenuInfo menuInfo){
    getActivity().getMenuInflater().inflate(R.menu.context_resource, menu);
  }
  
  /** registering ContextMenu*/
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState){
    View view = super.onCreateView(inflater, container, savedInstanceState);
    
    ListView list = (ListView)view.findViewById(android.R.id.list);
    registerForContextMenu(list);
    
    return view;
  }
  
  /**responding to Click*/
  @Override
  public boolean onContextItemSelected(MenuItem item){
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
    int position = info.position;
    CostumiseAdapter adapter = (CostumiseAdapter)getListAdapter();
    ImagineItem i = adapter.getItem(position);
    
    //TODO operation that need to be done
    int id = item.getItemId();
    if(id == R.id.item_edit){
      //do what it's need to be done
    }
    
    return super.onContextItemSelected(item);
  }
  

  private ArrayList createSomeItems() {
    ArrayList ret  = new ArrayList();
    for(int i = 0; i < 30; i++){
      ret.add(new ImagineItem(i));
    }
    return ret;
  }
  
  /**
   * @author Peter Gostincar
   * costumise adapter to show more than just Strings
   */
  private class CostumiseAdapter extends ArrayAdapter{

    public CostumiseAdapter(ArrayList items) {
      super(getActivity(), 0, items);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
      if(convertView == null){
        convertView = getActivity().getLayoutInflater()
            .inflate(R.layout.scroll_fragment, null);
      }
      
      ImagineItem item = getItem(position);
      
      TextView text = (TextView) convertView.findViewById(R.id.text_view);
      text.setText(item.mString);
      
      RadioButton b1 = (RadioButton) convertView.findViewById(R.id.radio_b1);
      b1.setChecked(item.mB1);
      
      RadioButton b2 = (RadioButton) convertView.findViewById(R.id.radio_b2);
      b2.setChecked(item.mB2);
      
      CheckBox cB = (CheckBox) convertView.findViewById(R.id.check_box);
      cB.setChecked(item.mB2);

      return convertView;
    }
  }

  /**
   * @author Peter Gostincar
   * class just for creating list of objects
   */
  private class ImagineItem{
    
    String mString = "Tralalal: ";
    boolean mCheckBox;
    boolean mB1;
    boolean mB2;
    
    public ImagineItem(int i) {
      mString += i;
      if(i % 2 == 0){
        mCheckBox = true;
      }
      int x = (int) (Math.random()*3+1);
      if(x == 1)
        mB1 = true;
      if(x == 2)
        mB2 = true;
    }
  }
}

menu/context_resource.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@+id/item_edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="@string/update"
        />
</menu>

activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

scroll_fragmnet.xml
<?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" >

    <CheckBox
        android:id="@+id/check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:focusable="false" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/check_box"
        android:padding="8dp" />

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_view"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radio_b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_one"
            android:focusable="false" />

        <RadioButton
            android:id="@+id/radio_b2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_two"
            android:focusable="false" />

    </RadioGroup>

</RelativeLayout>




Saturday 2 November 2013

Android : Creating fragment tutorial

How to create fragment in Android?

Here are two examples.
In the first we  create it from Activity class.
In the second we create it from a layout.xml file.

First Example:

package com.mamutek.adding.fragment.android;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

/**
 * @author Peter Gostincar
 */

public class MainActivity extends FragmentActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    FragmentManager fm = getSupportFragmentManager();
    Fragment f = fm.findFragmentById(R.id.fragmentContainer);
    
    if(f == null){
      f = new MainFragment();
      fm.beginTransaction()
        .add(R.id.fragmentContainer, f)
        .commit();
    }
  }
}

package com.mamutek.adding.fragment.android;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class MainFragment extends Fragment{
  
private TextView mText;
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_main, parent, false);
    
    mText = (TextView) v.findViewById(R.id.textView);
    mText.setText("From Activity");
    
    return v;
  }
}
activiti_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


Second Example:

package com.mamutek.fragment.from.xml;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

public class MainActivity extends FragmentActivity {

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

package com.mamutek.fragment.from.xml;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class MainFragment extends Fragment{
  
  private TextView mText;
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_main, parent, false);
    
    mText = (TextView) v.findViewById(R.id.textView);
    mText.setText("From Layout");
    
    return v;
  }
}
activiti_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.mamutek.fragment.from.xml.MainFragment"
    />
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Android : The scroll list tutorial

For make scrollable list fragment in Android!
MainActivity class is hosting the ScrollFragment class which extends ListFragment.
The commented code in public void onCreate(Bundle savedInstanceState) method is usable when we wanna just show the list of the strings. To achieve that you have to override the toString() method in Item class.

If we wanna intersect the on click listener we override method public void onListItemClick(ListView l, View v, int position, long id), and in layout (xml) set all focusable objects to  android:focusable="false".

With CostumiseAdapter which extends the ArrayAdapter<T>, is possible to display also other stuff.
You can get all code include xml files in Peter Gostincar Android.
This is the result of the following code.




package com.mamutek.com.contact.intent;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;

/**
 * @author Peter Gostincar
 */

public class MainActivity extends FragmentActivity {

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

  FragmentManager fm = getSupportFragmentManager();
  Fragment f = fm.findFragmentById(R.id.fragmentContainer);

  if(f == null){
   f = new MainFragment();
   fm.beginTransaction()
   .add(R.id.fragmentContainer, f)
   .commit();
  }
 }
}

package com.mamutek.scroll.list.android;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class ScrollFragment extends ListFragment{

 private ArrayList mItems;

 @Override
 public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  getActivity().setTitle("Title");
  mItems = createSomeItems();
  
  //*****this will show only Strings *****//
//  ArrayAdapter adapter = new ArrayAdapter
//         (getActivity(),
//         android.R.layout.simple_list_item_1,
//         mItems);
  CostumiseAdapter adapter = new CostumiseAdapter(mItems);
  setListAdapter(adapter);
 }
 
 @Override
 public void onListItemClick(ListView l, View v, int position, long id){
  Item item = (Item)(getListAdapter()).getItem(position);
  Log.d("TRA" , item.toString());
  //the item is clicked Object on the list...
 }

 private ArrayList createSomeItems() {
  ArrayList ret  = new ArrayList();
  for(int i = 0; i < 30; i++){
   ret.add(new Item(i));
  }
  return ret;
 }
 
 /**
  * @author Peter Gostincar
  * costumise adapter to show more than just Strings
  */
 private class CostumiseAdapter extends ArrayAdapter{

  public CostumiseAdapter(ArrayList items) {
   super(getActivity(), 0, items);
  }
  
  @Override
  public View getView(int position, View convertView, ViewGroup parent){
   if(convertView == null){
    convertView = getActivity().getLayoutInflater().inflate(R.layout.scroll_fragment, null);
   }
   
   Item item = getItem(position);
   
   TextView text = (TextView) convertView.findViewById(R.id.text_view);
   text.setText(item.mString);
   
   RadioButton b1 = (RadioButton) convertView.findViewById(R.id.radio_b1);
   b1.setChecked(item.mB1);
   
   RadioButton b2 = (RadioButton) convertView.findViewById(R.id.radio_b2);
   b2.setChecked(item.mB2);
   
   CheckBox cB = (CheckBox) convertView.findViewById(R.id.check_box);
   cB.setChecked(item.mB2);

   return convertView;
  }
 }

 /**
  * @author Peter Gostincar
  * class just for creating list of objects
  */
 private class Item{
  
  String mString = "Tralalal: ";
  boolean mCheckBox;
  boolean mB1;
  boolean mB2;
  
  public Item(int i) {
   mString += i;
   if(i % 2 == 0){
    mCheckBox = true;
   }
   int x = (int) (Math.random()*3+1);
   if(x == 1)
    mB1 = true;
   if(x == 2)
    mB2 = true;
  }
  
  @Override
  public String toString(){
   return mString;
  }
 }
}
<?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" >

    <CheckBox
        android:id="@+id/check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:focusable="false" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/check_box"
        android:padding="8dp" />

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_view"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radio_b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_one"
            android:focusable="false" />

        <RadioButton
            android:id="@+id/radio_b2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_two"
            android:focusable="false" />

    </RadioGroup>

</RelativeLayout>