Monday 15 May 2017

how to read json file from assets folder in android

if the question as json array like follwing


[{"questionId":"Q18868","questionValue":"What is the minimum age for obtaining an Alabama driver license?","choice1":"At least 16 years.","choice2":"At least 17 years.","choice3":"At least 18 years.","choice4":"At least 19 years.","answer":"1","imageName":"NA"},{"questionId":"Q18873","questionValue":"Whether Alabama license may be issued to persons under age 19 years, without secondary school graduation or current attendance?","choice1":"No.","choice2":"Yes.","choice3":"Yes, on special permission.","choice4":"Any thing else.","answer":"1","imageName":"NA"},{"questionId":"Q19001","questionValue":"For how many moving traffic violations on a GDL (graduated driver license), you license will be suspended?","choice1":"1 or more.","choice2":"2 or more.","choice3":"3 or more.","choice4":"4 or more.","answer":"2","imageName":"NA"},{"questionId":"Q19323","questionValue":"For which persons Graduated Driver License (GDL) system is not applicable?","choice1":"Persons aged 18 years or older.","choice2":"Persons aged 17 or older with valid driver license for 6 months.","choice3":"Persons aged 16 or older, who are married or head of a household.","choice4":"All the above persons.","answer":"4","imageName":"NA"},{"questionId":"Q19324","questionValue":"Whether persons who have been legally relieved of minority status, is eligible for GDL system?","choice1":"NO.","choice2":"Yes.","choice3":"Yes, if under 16 years.","choice4":"Any thing else.","answer":"1","imageName":"NA"},{"questionId":"Q19325","questionValue":"Who should accompany a person aged 15 years with learner\u0027s license in the vehicle, while driving?","choice1":"A parent or legal guardian.","choice2":"A licensed driver aged 21 years or older.","choice3":"A licensed or certified driving instructor.","choice4":"Any one of the above persons.","answer":"4","imageName":"NA"},{"questionId":"Q19326","questionValue":"In which seat of the vehicle, the person accompanying the driver aged 15 years with learner\u0027s license should sit?","choice1":"Seat next to the driver.","choice2":"Any front seat.","choice3":"Seat behind the driver.","choice4":"Any where else.","answer":"1","imageName":"NA"}]



JsonParser .java

package com.alabama;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;

public class JsonParser {

String fileName;
Activity activity;
public JsonParser(Activity activity,String fileName) {
this.activity=activity;
this.fileName=fileName;
}
public ArrayList<QuestBeen> getQuestion() {
ArrayList<QuestBeen> list=new ArrayList<QuestBeen>();
JSONArray array;
try {
array = new JSONArray(loadJSONFromAsset());
for(int i=0;i<array.length();i++){
JSONObject json_data = array.getJSONObject(i);
QuestBeen been=new QuestBeen();
been.setQuestionId(json_data.getString("questionId"));
been.setQuestionValue(json_data.getString("questionValue"));
been.setChoice1(json_data.getString("choice1"));
been.setChoice2(json_data.getString("choice2"));
been.setChoice3(json_data.getString("choice3"));
been.setChoice4(json_data.getString("choice4"));
been.setAnswer(json_data.getString("answer"));
list.add(been);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
public String loadJSONFromAsset() {
   String json = null;
   try { 
       InputStream is = activity.getAssets().open(fileName);
       int size = is.available();
       byte[] buffer = new byte[size];
       is.read(buffer);
       is.close();
       json = new String(buffer, "UTF-8");
   } catch (IOException ex) {
       ex.printStackTrace();
       return null; 
   } 
   return json;
}
}


reading files in the activity



package com.alabama;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class TestActivity extends Activity{
int ans=0;
int id=0;
int rightValue=0;
ArrayList<QuestBeen> question;
JsonParser parser;
TextView textViewQuestion,textViewHead;
RadioGroup group;
RadioButton choice1,choice2,choice3,choice4;
Button buttonPrev,buttonNext;
int pos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pos=getIntent().getExtras().getInt("position");
pos=10+pos;
parser=new JsonParser(TestActivity.this,"QC"+pos+".json");
System.out.println("--------------------------");
Log.d("json ", parser.loadJSONFromAsset().toString());
question=parser.getQuestion();
GUI();
}
private void GUI() {
textViewQuestion=(TextView)findViewById(R.id.textViewQuestion);
textViewHead=(TextView)findViewById(R.id.textViewHead);
group=(RadioGroup)findViewById(R.id.radioGroup1);
choice1=(RadioButton)findViewById(R.id.radio0);
choice2=(RadioButton)findViewById(R.id.radio1);
choice3=(RadioButton)findViewById(R.id.radio2);
choice4=(RadioButton)findViewById(R.id.radio3);
textViewHead.setText("1/"+question.size());
ConstantValues.totaQuestin=question.size();
buttonPrev=(Button)findViewById(R.id.button1);
buttonNext=(Button)findViewById(R.id.button2);
setVal();
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
 
 
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
int idx = group.indexOfChild(radioButton);
if(idx==ans){
rightValue=1;
}
else
rightValue=0;  
//Toast.makeText(getApplicationContext(), idx+"---", Toast.LENGTH_SHORT).show();
}
});
buttonNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ConstantValues.answers.add(id,rightValue);
id++;
Log.d("question", id+"--");
if(id<=question.size()-1)
setVal();
else{
Toast.makeText(getApplicationContext(), "Result", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(TestActivity.this,ResultActivity.class);
startActivity(intent);
}
Log.d("-----------", ConstantValues.answers.toString());
}
});
buttonPrev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
id--;
Log.d("question", id+"--");
if(id<=0){
id=0;
Toast.makeText(getApplicationContext(), "No Questions", Toast.LENGTH_SHORT).show();
}
else
setVal();
}
});
}

private void setVal() {
ans=Integer.parseInt(question.get(id).getAnswer());
group.clearCheck();
textViewHead.setText(id+"/"+question.size());
textViewQuestion.setText(question.get(id).getQuestionValue());
choice1.setText(question.get(id).getChoice1());
choice2.setText(question.get(id).getChoice2());
choice3.setText(question.get(id).getChoice3());
choice4.setText(question.get(id).getChoice4());
}

 
}







Tuesday 18 April 2017

Android Custom Calendar

CalendarAdapter.java


import android.content.Context;
import android.graphics.Color;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.GregorianCalendar;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;




/** * Created by Mafiree on 11/7/2016. */
public class CalendarAdapter extends BaseAdapter {
    private Context mContext;

    private java.util.Calendar month;
    public GregorianCalendar pmonth; // calendar instance for previous month    /**     * calendar instance for previous month for getting complete view     */    public GregorianCalendar pmonthmaxset;
    private GregorianCalendar selectedDate;
    int firstDay;
    int maxWeeknumber;
    int maxP;
    int calMaxP;
    int lastWeekDay;
    int leftDays;
    int mnthlength;
    String itemvalue, curentDateString;
    DateFormat df;

    private ArrayList<String> items;
    public static List<String> dayString;
    private View previousView;

    public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {

        CalendarAdapter.dayString = new ArrayList<String>();
        month = monthCalendar;
        selectedDate = (GregorianCalendar) monthCalendar.clone();
        mContext = c;
        month.set(GregorianCalendar.DAY_OF_MONTH, 1);
        this.items = new ArrayList<String>();
        df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        curentDateString = df.format(selectedDate.getTime());
        refreshDays();
    }

    public void setItems(ArrayList<String> items) {
        for (int i = 0; i != items.size(); i++) {
            if (items.get(i).length() == 1) {
                items.set(i, "0" + items.get(i));
            }
        }
        this.items = items;
    }

    public int getCount() {
        return dayString.size();
    }

    public Object getItem(int position) {
        return dayString.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new view for each item referenced by the Adapter    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        TextView dayView;
        if (convertView == null) { // if it's not recycled, initialize some            // attributes            LayoutInflater vi = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.calendar_item, null);

        }
        dayView = (TextView) v.findViewById(R.id.date);
        // separates daystring into parts.        String[] separatedTime = dayString.get(position).split("-");
        // taking last part of date. ie; 2 from 2012-12-02        String gridvalue = separatedTime[2].replaceFirst("^0*", "");
        // checking whether the day is in current month or not.        if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
            // setting offdays to white color.            dayView.setTextColor(Color.WHITE);
            dayView.setClickable(false);
            dayView.setFocusable(false);
        } else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
            dayView.setTextColor(Color.WHITE);
            dayView.setClickable(false);
            dayView.setFocusable(false);
        } else {
            // setting curent month's days in blue color.            dayView.setTextColor(Color.BLUE);
        }

        if (dayString.get(position).equals(curentDateString)) {
            setSelected(v);
            previousView = v;
        } else {
           // v.setBackgroundResource(R.drawable.list_item_background);        }
        dayView.setText(gridvalue);

        // create date string for comparison        String date = dayString.get(position);

        if (date.length() == 1) {
            date = "0" + date;
        }
        String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
        if (monthStr.length() == 1) {
            monthStr = "0" + monthStr;
        }

        // show icon if date is not empty and it exists in the items array        ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
        if (date.length() > 0 && items != null && items.contains(date)) {
            iw.setVisibility(View.VISIBLE);
        } else {
            iw.setVisibility(View.INVISIBLE);
        }
        return v;
    }

    public View setSelected(View view) {
        if (previousView != null) {
            //previousView.setBackgroundResource(R.drawable.list_item_background);        }
        previousView = view;
      //  view.setBackgroundResource(R.drawable.calendar_cel_selectl);        return view;
    }

    public void refreshDays() {
        // clear items        items.clear();
        dayString.clear();
        pmonth = (GregorianCalendar) month.clone();
        // month start day. ie; sun, mon, etc        firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
        // finding number of weeks in current month.        maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
        // allocating maximum row number for the gridview.        mnthlength = maxWeeknumber * 7;
        maxP = getMaxP(); // previous month maximum day 31,30....        calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...        /**         * Calendar instance for getting a complete gridview including the three         * month's (previous,current,next) dates.         */        pmonthmaxset = (GregorianCalendar) pmonth.clone();
        /**         * setting the start date as previous month's required date.         */        pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);

        /**         * filling calendar gridview.         */        for (int n = 0; n < mnthlength; n++) {

            itemvalue = df.format(pmonthmaxset.getTime());
            pmonthmaxset.add(GregorianCalendar.DATE, 1);
            dayString.add(itemvalue);

        }
    }

    private int getMaxP() {
        int maxP;
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMinimum(GregorianCalendar.MONTH)) {
            pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
                    month.getActualMaximum(GregorianCalendar.MONTH), 1);
        } else {
            pmonth.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) - 1);
        }
        maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

        return maxP;
    }

}





public class CalendarView extends Activity {

public GregorianCalendar month, itemmonth;
public CalendarAdapter adapter;// adapter instance public Handler handler;// for grabbing some event values for showing the dot // marker. public ArrayList<String> items; // container to store calendar items which // needs showing the event marker public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calendar); month = (GregorianCalendar) GregorianCalendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();
items = new ArrayList<String>(); adapter = new CalendarAdapter(this, month); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(adapter); handler = new Handler(); handler.post(calendarUpdater); TextView title = (TextView) findViewById(R.id.title); title.setText(android.text.format.DateFormat.format("MMMM yyyy", month)); RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous); previous.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setPreviousMonth(); refreshCalendar(); } }); RelativeLayout next = (RelativeLayout) findViewById(R.id.next); next.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setNextMonth(); refreshCalendar(); } }); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ((CalendarAdapter) parent.getAdapter()).setSelected(v); String selectedGridDate = CalendarAdapter.dayString .get(position); String[] separatedTime = selectedGridDate.split("-"); String gridvalueString = separatedTime[2].replaceFirst("^0*", "");// taking last part of date. ie; 2 from 2012-12-02. int gridvalue = Integer.parseInt(gridvalueString); // navigate to next or previous month on clicking offdays. if ((gridvalue > 10) && (position < 8)) { setPreviousMonth(); refreshCalendar(); } else if ((gridvalue < 7) && (position > 28)) { setNextMonth(); refreshCalendar(); } ((CalendarAdapter) parent.getAdapter()).setSelected(v); showToast(selectedGridDate); } }); } protected void setNextMonth() { if (month.get(Calendar.MONTH) == month.getActualMaximum(Calendar.MONTH)) { month.set((month.get(Calendar.YEAR) + 1), month.getActualMinimum(Calendar.MONTH), 1); } else { month.set(Calendar.MONTH, month.get(Calendar.MONTH) + 1); } } protected void setPreviousMonth() { if (month.get(Calendar.MONTH) == month.getActualMinimum(Calendar.MONTH)) { month.set((month.get(Calendar.YEAR) - 1), month.getActualMaximum(Calendar.MONTH), 1); } else { month.set(Calendar.MONTH, month.get(Calendar.MONTH) - 1); } } protected void showToast(String string) { Toast.makeText(this, string, Toast.LENGTH_SHORT).show(); } public void refreshCalendar() { TextView title = (TextView) findViewById(R.id.title); adapter.refreshDays(); adapter.notifyDataSetChanged(); handler.post(calendarUpdater); // generate some calendar items title.setText(android.text.format.DateFormat.format("MMMM yyyy", month)); } public Runnable calendarUpdater = new Runnable() { @Override public void run() { items.clear(); // Print dates of the current week DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String itemvalue; for (int i = 0; i < 7; i++) { itemvalue = df.format(itemmonth.getTime()); itemmonth.add(Calendar.DATE, 1); items.add("2012-09-12"); items.add("2012-10-07"); items.add("2012-10-15"); items.add("2012-10-20"); items.add("2012-11-30"); items.add("2012-11-28"); } adapter.setItems(items); adapter.notifyDataSetChanged(); } }; }

Friday 10 February 2017

Making TextView scrollable in Android

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);

PagerAdapter Class

This is the main activity


myPagerAdapter=new MyPagerAdapter(TopNewsAcivity.this,arrayList);
verticalViewPager=(VerticalViewPager)findViewById(R.id.view_pager);
verticalViewPager.setAdapter(myPagerAdapter);


For dynamic PagerAdapter

MyPagerAdapter .class

package news.com.mynews.adapter;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.ActionBarOverlayLayout.LayoutParams;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import news.com.mynews.R;
import news.com.mynews.bean.NewsBean;

/** * Created by Mafiree on 12/19/2016. *///http://android-er.blogspot.in/2014/04/example-of-viewpager-with-custom.htmlpublic class MyPagerAdapter extends PagerAdapter {


    int NumberOfPages = 5;

    int[] res = {
            android.R.drawable.ic_dialog_alert,
            android.R.drawable.ic_menu_camera,
            android.R.drawable.ic_menu_compass,
            android.R.drawable.ic_menu_directions,
            android.R.drawable.ic_menu_gallery};
    int[] backgroundcolor = {
            0xFF101010,
            0xFF202020,
            0xFF303030,
            0xFF404040,
            0xFF505050};

    Activity activity;
    ArrayList<NewsBean> list;

    public MyPagerAdapter(Activity activity,ArrayList<NewsBean> list) {
        this.activity=activity;
        this.list=list;
    }

    @Override
    public int getCount() {
        //return NumberOfPages;        return list.size();
    }

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

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

        ImageView imageView=new ImageView(activity);
        imageView.setScaleType(ScaleType.FIT_XY);

        TextView textView = new TextView(activity);
        textView.setTextColor(Color.BLACK);
       // textView.setTextSize(18);        textView.setTypeface(Typeface.DEFAULT_BOLD);
        //textView.setText(String.valueOf(position));      //  textView.setText(list.get(position).getTitle());        int n=200;
        String upToNCharacters = list.get(position).getDescription().substring(0, Math.min(list.get(position).getDescription().length(), n));

        textView.setText(Html.fromHtml("<h2>"+list.get(position).getTitle()+"</h2><br><p>"+upToNCharacters+" here</p>"));

        TextView textContent=new TextView(activity);
//        textContent.setText(Color.WHITE);        textContent.setTextColor(Color.GRAY);
       // textContent.setTextSize(16);       // textContent.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));        System.out.println("*******************************************");
        String imageUrl=null;
        imageUrl="http://bestcinema.in/wp-content/uploads/"+list.get(position).getImageURL();
       
        try {
            Picasso.with(activity).load(imageUrl).resize(250,350).into(imageView);
        }catch (Exception e){
            e.printStackTrace();
        }

        LayoutParams imageParams = new LayoutParams(
                LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(imageParams);

        LinearLayout layout = new LinearLayout(activity);
        layout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        //layout.setBackgroundColor(Color.BLUE);        layout.setLayoutParams(layoutParams);

        layout.addView(imageView);
        layout.addView(textView);
        layout.addView(textContent);

        final int page = position;
        layout.setPadding(7,7,7,7);


        LinearLayout layoutBotom = new LinearLayout(activity);
        layoutBotom.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams layoutParamsBottom = new LayoutParams(
                LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        //layout.setBackgroundColor(Color.BLUE);        layoutBotom.setLayoutParams(layoutParamsBottom);


        ImageView imageViewShare=new ImageView(activity);
        imageViewShare.setBackgroundResource(R.drawable.ic_menu_share);

        ImageView imageViewSend=new ImageView(activity);
        imageViewSend.setBackgroundResource(R.drawable.ic_menu_send);

        layoutBotom.addView(imageViewShare);
        layoutBotom.addView(imageViewSend);

        layout.addView(layoutBotom);

        container.addView(layout);
        return layout;
    }

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


}

For Static PagerAdapter


class CustomPagerAdapter extends PagerAdapter {
    Context mContext;
    LayoutInflater mLayoutInflater;
    public CustomPagerAdapter(Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return mResources.length;
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageView.setImageResource(mResources[position]);
        container.addView(itemView);
        return itemView;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}