Category Archives: Android App development

Read data from GitHub hosted json file in Flutter


This is my first flutter tutorial, which explain how you can host and read json data from GitHub repository.

First up all you need to host json in GitHub Page , here is the complete guide. After that you can read the data using http package in Flutter.

First up all you need to specify the pubspec.yml settings as follows

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2

Go to your pubspec file and add the high lighted sections to use the network/web connection.

Now we need a Model class to read and hold the json object. Eventually the fetchpost Future will extract the data from GitHub.

Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}

A special function called FutureBuilder help us to feched post object.Here is the complete main.dart file

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  Future<Post> post;
  void initState() {
    super.initState();
    post = fetchPost();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: FutureBuilder<Post>(
        future: post,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return new ListView(children: <Widget>[
              new Text("Q:" + snapshot.data.question),
              new Text("A:" + snapshot.data.answer)
            ]);
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          // By default, show a loading spinner
          return CircularProgressIndicator();
        },
      )),
      floatingActionButton: FloatingActionButton(
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Post {
  final String question;
  final String answer;
  final String catagory;
  Post({this.question, this.answer, this.catagory});
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        question: json['question'],
        answer: json['answer'],
        catagory: json['catagory']);
  }
}

Insert if not exist sqllite [android]


We are femiliar with if not exits keyword when working sqllite database in Android or in web applications as well.

If not exist work with create statements, so how do we implement the same tactics in insert statement ?

Here what I found ,

Take a look at what we have

Here I got a table Entries which keep track of different entries with auto grnerated eid column. I wanna make happends only insert entries that is not exist in the table.entries.pngTodo

  1. Create a unique index on ename column
  2. usere insert or ignore into statement instead of insert into
Index the colum
create unique index Entry_name_start on Entries ( ename ) ;

This will generate a intex on column ename, which means it can’t be duplicated

The new insert insert.png
insert or ignore into "Entries" (
    id,
    ename)
values (
    :id,
    :ename)
;

It will work….

Note: I used Android Studio and plugin called DB Browser in this tutorial

Ways you can handle button click in Android Studio Project


In a Android project you need to handle button click for completion of data processing, a double click maiy not enough create automatic Event handler as in Microsoft visual Studio projects. You have to do it in Java style.

You have two options, one is to handle click in Oncreate method or simply add new Method and attach it to the Onclick property [Layout]

 The first Method

Most of the coders love this method and it can save time as well. The code reside in OnCreate method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    
    textView = (TextView) findViewById(R.id.text1);
    Button button2=findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setText("I clciked button2 - Oncreate");
        }
    });
     
}
The Second Method

This will require Create a Public Method with View as argument. Keep in mind that all controls should be declared just below the beggining of the class and assing controls at OnCreate method

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         
        textView = (TextView) findViewById(R.id.text1);
   
    }
The hadler method

Place the code after the OnCreate

public void ButtonClick1(View view) {
    textView.setText("I Clicked Button1");
}

Go to the layout and  find the onclick property of the button ther you will see the ButtonClick1 choose the right one

or you can configure it in the XML file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="ButtonClick1"
            android:text="OnClick 1"
            tools:layout_editor_absoluteX="30dp"
            tools:layout_editor_absoluteY="58dp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Onclick 2"
            tools:layout_editor_absoluteX="128dp"
            tools:layout_editor_absoluteY="58dp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Watch the tutorial video on Youtube

I think this was enough for begiiners, leave comments and questions below

 

 

 

 

Howto start a new activity in Android Studio


Activity in Android studio represent a Window, where you can dispplay controls and handle data etc. You can start as many form/activity the project requires. Just add a new Activity and do the following

Here we goes

  • Create a Intenet object, the first parameter will be the package or Main activity and the second will be the new new activity class
  • Call the startActivity method

Code

Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);

Note: Can also possible to run as many activity with in a activity using the concept Fragment (Learn More about Fragments )
I hope this will help you

How to configure Nox Emulator for Android Studio


Nox Player is one of the coolest Android Emulater for playing Android Games as well as for Application Developement and Testing.  You can use the Emulator to run app you are developing with Android Studio.2018-08-30_222153

  1. Download the Nox Player from the web and Install the software.[Make sure that you had installed graphics driver properly, otherwise the installation may fail].
  2. Start Nox Player, you can switch between Tablet to Mobile view by changing Advanced Settings in Nox.
  3. Let’s Turn on Developer Option by Clicking 3 or four times in Build number  [About Phone in Nox]
  4. Also Turn on USB Debugging [Developer Option]
  5. Final step is to run the adb command with ip address in command prompt. [adb resides in Nox’s bin folder]

adb  command [ run on command prompt]

nox_adb.exe connect 127.0.0.1:62001

Optionaly you can create and run a batch file wich can be used to run Nox adb  with a single click. Please make sure your batch file resides in the same bin folder where Nox player file found.[Use right click Nox Player short Cut to find the location in Windows].

You can download the batch file from Github and move to the bin folder

  • Now Start the Android Studio
  • Also start the Noxplayer and Turn on Developer option
  • Run the adb
  • Try debug App in Adroid Studio and it will be start appearing in the device list, otherwise run the adb with Run as admin a and  try again

 

How to create ListView with CustomAdapter in Android Studio


Default ListView layout let you display single piece of information while a customised list view layout let you design your own components. All you need is a separate layout file

1

and a adaptor which extends BaseAdpter or ArrayAdapter. Continue reading