Getting Data from Local JSON and set Json Data into a TextView which is to be swipable(View Pager) in Android
Create assets folder and put json.json file.
Inside of an Activity:
ViewPager myPager = null;
int count1 = 0;
Timer timer;
ArrayList<String> title1;
ArrayList<String> title2;
JSONArray jsonArray;
JSONObject jsonObject;
String m;
String movie;
String category;
InputStream inputstream;
BufferedReader reader;
int pager_position;
callingJsonFunction();
getData();
setTime_ToSlide();
private void callingJsonFunction() {
try {
inputstream = getResources().getAssets().open("json.json");
reader = new BufferedReader(new InputStreamReader(inputstream));
m = reader.toString();
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
m = total.toString();
} catch (IOException ex) {
Toast.makeText(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private void getData() {
title1 = new ArrayList<>();
title2 = new ArrayList<>();
try {
jsonObject = new JSONObject(m);
jsonArray = jsonObject.optJSONArray("Quotes");
int arraylength = jsonArray.length();
Log.e("Json Length", String.valueOf(arraylength));
for (int i = 0; i < arraylength; i++) {
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
movie = jsonChildNode.optString("Quote").toString();
category = jsonChildNode.optString("Author").toString();
title1.add(movie);
title2.add(category);
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private void setTime_ToSlide() {
TextSlideShowAdapter adapter = new TextSlideShowAdapter(MainActivity.this, title1, title2);
myPager = (ViewPager) findViewById(R.id.reviewpager);
myPager.setAdapter(adapter);
// myPager.setCurrentItem(0);
// Log.e("Marysudha", "PagerPosition" + pager_position);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (count1 <= 116) {
myPager.setCurrentItem(count1);
pager_position = myPager.getCurrentItem();
count1++;
} else {
count1 = 0;
myPager.setCurrentItem(count1);
}
}
});
}
}, 500, 7000);
}
json.json
{
"Quotes":[
{
"Quote":"Let your heart,do not be troubled",
"Author":" xxxxxxx"
},
{
"Quote":"The Lord is my Shepherd",
"Author":"Psalm 23:1"
},
{
"Quote":"The will show them wonders",
"Author":"xxxxxxx"
}
]
}
{.........} ---> Json Object
[.........] ----> Json Array
Comments
Post a Comment