How to Add One Side Left Border to TextView in Android using XML

 One side border is most probably used to show text into Flag view. Using the one side border we could make the TextView more good looking. So here is the complete step by step tutorial for How to Add One Side Left Border to TextView in Android using XML.

How to Add One Side Left Border to TextView in Android using XML

How to Add One Side Left Border to TextView in Android :

Code for MainActivity.java file.

package com.android_examples.onesidebordertextview_android_examplescom; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?> <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" android:background="#fff" tools:context="com.android_examples.onesidebordertextview_android_examplescom.MainActivity"> <TextView android:layout_width="fill_parent" android:layout_height="100dp" android:text="This is Sample TextView Text." android:background="@drawable/text_style" android:gravity="center" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_margin="12dp" android:textSize="20dp" android:textColor="#000" /> </RelativeLayout>

Code for text_style.xml file.

<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#F44336"/> </shape> </item> <item android:left="4dp"> <shape android:shape="rectangle"> <solid android:color="#FFEB3B"/> </shape> </item> </layer-list>

Screenshot :

Android Save Download Image from WebView on Long Press Image Tutorial

 Advance modern mobile application web browsers can give the facility to its users to Download Image instantly on Image Long Press event in WebView. So in this tutorial we would going to make a android application in android studio to Download-Save image in mobile phone gallery on Image Long Press.

Contents in this project Save Download Image from WebView on Long Press Image Tutorial :

1. Add Internet permission in AndroidManifest.xml file. Internet permission is very important because without the internet permission we cannot open any webpage in WebView.

<uses-permission android:name="android.permission.INTERNET"/>

2. Create WebView widget in activity_main.xml file.

<WebView android:id="@+id/WebView1" android:layout_width="fill_parent" android:layout_height="fill_parent" />

3. Create WebView object and String URL in MainActivity.java file.

WebView webView; String HTTP_URL = "https://www.google.com" ;

4. Assign ID to WebView.

webView = (WebView)findViewById(R.id.WebView1);

5. Now enable the JavaScript in WebView and setWebViewClient and finally load the String URL into WebView.

webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); registerForContextMenu(webView); webView.loadUrl(HTTP_URL);

5. Now create onCreateContextMenu override method to create the Context menu in Alert box to download and save the image into Mobile phone gallery.

@Override public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){ super.onCreateContextMenu(contextMenu, view, contextMenuInfo); final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult(); if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE || webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) { contextMenu.setHeaderTitle("Download Image From Below"); contextMenu.add(0, 1, 0, "Save - Download Image") .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { String DownloadImageURL = webViewHitTestResult.getExtra(); if(URLUtil.isValidUrl(DownloadImageURL)){ DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); downloadManager.enqueue(request); Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show(); } return false; } }); } } }

 Final Source Code :

Code for MainActivity.java file.

package com.android_examples.saveimagefromwebview_android_examplescom; import android.app.DownloadManager; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.webkit.URLUtil; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView webView; String HTTP_URL = "https://www.google.com" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView)findViewById(R.id.WebView1); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); registerForContextMenu(webView); webView.loadUrl(HTTP_URL); } @Override public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){ super.onCreateContextMenu(contextMenu, view, contextMenuInfo); final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult(); if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE || webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) { contextMenu.setHeaderTitle("Download Image From Below"); contextMenu.add(0, 1, 0, "Save - Download Image") .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { String DownloadImageURL = webViewHitTestResult.getExtra(); if(URLUtil.isValidUrl(DownloadImageURL)){ DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); downloadManager.enqueue(request); Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show(); } return false; } }); } } }

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?> <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" tools:context="com.android_examples.saveimagefromwebview_android_examplescom.MainActivity"> <WebView android:id="@+id/WebView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android_examples.saveimagefromwebview_android_examplescom"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Screenshots:

Download Image


Android Create Navigation Drawer Using Fragments Example Tutorial

 The navigational drawer is a complete layout box that contain a left side sliding menu panel with multiple icons. Each icon associated with a individual screen or Fragment. The left side sliding window is used to show all the navigational menu present in app so it will be more easy for app user to visit complete app with one tap. So in this tutorial we would going to create a android app with Navigation Drawer Using Fragments complete step by step Example Tutorial.

Android Create Navigation Drawer Using Fragments Example Tutorial

1. Start a fresh android application project in Android Studio and select the Navigation Drawer Screen as default screen.

2. If you have already created the project then you can also add Navigation drawer activity in your existing project by opening Your Package Name -> New -> Activity -> Navigation Drawer Activity.

Now we would run our newly created app in Simulator and we would see that the Navigational drawer View is successfully created in our app.

This above Navigation Drawer View is default view . Now next step is to make changes in this code. So let’s get started ðŸ™‚ .

Start Coding :

1. Open the default activity_main_drawer.xml file present in res->menu folder. This file is used as our Menu file. I am creating only 2 menus in navigation drawer.

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="Camera" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="Gallery" /> </group> </menu>

2. Now we would make the View layout for Navigational Drawer. So right click on res -> layout ->New -> XML -> Layout XML file. Now we would make 2 layout files 1st is fragment_layout_1 and 2nd is fragment_layout_2 .

Code for fragment_layout_1.xml file.

<?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:layout_margin="10dp"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textSize="25dp" android:text="This is Camera Menu Layout." android:textAlignment="center"/> </RelativeLayout>

Code for fragment_layout_2.xml file.

<?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:layout_margin="10dp"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textSize="25dp" android:text="This is Gallery Menu Layout." android:textAlignment="center"/> </RelativeLayout>

3. Open the content_main.xml file and add a Frame Layout inside it.

<?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="com.android_examples.navigationdrawer_android_examplescom.MainActivity" tools:showIn="@layout/app_bar_main"> <FrameLayout android:id="@+id/frame_layout" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.constraint.ConstraintLayout>

4. Now create 2 Java classes named as Fragment_1.java and Fragment_2.java . The Fragment_1.java file called the fragment_layout_1.xml file and the Fragment_1.java file call the fragment_layout_2.xml file.

Code for Fragment_1.java file.

package com.android_examples.navigationdrawer_android_examplescom; import android.os.Bundle; import android.view.View; import android.support.v4.app.Fragment; import android.view.ViewGroup; import android.support.annotation.Nullable; import android.view.LayoutInflater; /** * Created by Juned on 11/19/2017. */ public class Fragment_1 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //returning our layout file //change R.layout.yourlayoutfilename for each of your fragments return inflater.inflate(R.layout.fragment_layout_1, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Fragment_1_Camera "); } }

Code for Fragment_2.java file.

package com.android_examples.navigationdrawer_android_examplescom; import android.os.Bundle; import android.view.View; import android.support.v4.app.Fragment; import android.view.ViewGroup; import android.support.annotation.Nullable; import android.view.LayoutInflater; /** * Created by Juned on 11/19/2017. */ public class Fragment_2 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //returning our layout file //change R.layout.yourlayoutfilename for each of your fragments return inflater.inflate(R.layout.fragment_layout_2, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Fragment_2_Gallery "); } }

5. Now file step is to write code in MainActivity.java file.

package com.android_examples.navigationdrawer_android_examplescom; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); //Add this line of code here to open the default selected menu on app start time. ShowFragment(R.id.nav_camera); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void ShowFragment(int itemId) { Fragment fragment = null; switch (itemId) { case R.id.nav_camera: fragment = new Fragment_1(); break; case R.id.nav_gallery: fragment = new Fragment_2(); break; } if (fragment != null) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame_layout, fragment); fragmentTransaction.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { //Calling the ShowFragment() method here to show the our created menu as default menus. ShowFragment(item.getItemId()); return true; } }

Screenshots:

Navigation Drawer

Android JSON Parsing Custom ListView From MySQL Database Tutorial

 JSON is the backbone of every dynamic android application because using JSON data we can send and receive data from online MySQL database server using PHP language. So in this tutorial we would going to store Fruit names online in MySQL database table and retrieve them inside android application in ListView using org.apache.http.legacy library. So here is the complete step by step tutorial for Android JSON Parsing Custom ListView From MySQL Database.

Android JSON Parsing Custom ListView From MySQL Database Tutorial

Contents in this project Android JSON Parsing Custom ListView From MySQL Database Tutorial :

1. Create a Database on your online or local MySQL PhpMyAdmin hosting server.

2. Create a Table named as Fruits_Name_Table inside the MySQL database with 2 columns id and Fruit_Name . Now set the id as primary key.

3. Now insert some records in this table manually. For example my table is for fruit names so i am inserting some common fruit names inside the MySQL table. Below is the screenshot of Table after inserting some records.

4. This step is very important. Now we would going to create 2 PHP files named as DBConfig.php and ShowFruitsName.php . Now we would upload them on online hosting web space using any File manager.

DBConfig.php : This file contain all the useful and recommended server configuration. Make any changes in this file according to your sever or MySQL database configuration.

ShowFruitsName.php : This file would fetch all the records from MySQL database table and show encode them in JSON format.

Code for DBConfig.php file.

<?php //Define your Database Host here. $HostName = "localhost"; //Define your database User Name here. $HostUser = "id3846509_android_user"; //Define your Database Password here. $HostPass = "123456"; //Define your database name here. $DatabaseName = "id3846509_android_db"; ?>

Code for ShowFruitsName.php file.

<?php include 'DBConfig.php'; $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM Fruits_Name_Table"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $TableItems = $row; $FinalJSON = json_encode($TableItems); } } else { echo "No Results Found in Table."; } echo $FinalJSON; $conn->close(); ?>

5. Import org.apache.http.legacy library inside your build.gradle(Module : App) file in android block.

6. Paste the useLibrary ‘org.apache.http.legacy’ code in android block like i did in below screenshot.

Here you go now the org.apache.http.legacy library would successfully installed in your Android Studio project.

7. Start Coding For App  :

Java Files in this project :

  1. MainActivity.java
  2. ListViewAdapter.java
  3. HttpWebServices.java
  4. FruitNames.java

Layout Files in this project :

  1. activity_main.xml
  2. listview_items.xml

Other Files :

  1. AndroidManifest.xml

Code for MainActivity.java file.

package com.android_examples.json_listview_android_examplescom; import android.support.v7.app.AppCompatActivity; import org.json.JSONException; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.os.AsyncTask; import android.widget.AdapterView; import android.widget.ProgressBar; import org.json.JSONArray; import android.os.Bundle; import android.view.View; import android.widget.ListView; import org.json.JSONObject; import android.widget.Toast; public class MainActivity extends AppCompatActivity { ListView FruitsNameListView; ProgressBar progressBar; String HttpServerURL = "https://androidjson27.000webhostapp.com/ShowFruitsName.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FruitsNameListView = (ListView)findViewById(R.id.listview1); progressBar = (ProgressBar)findViewById(R.id.progressBar); new GetServerResponseFunction(MainActivity.this).execute(); FruitsNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub FruitNames ListViewClickItem = (FruitNames) parent.getItemAtPosition(position); Toast.makeText(MainActivity.this, ListViewClickItem.getFruit_Name(), Toast.LENGTH_SHORT).show(); } }); } public class GetServerResponseFunction extends AsyncTask<Void, Void, Void> { public Context context; String DataHolder; List<FruitNames> fruitNamesList; public GetServerResponseFunction(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { HttpWebServices httpWebServices = new HttpWebServices(HttpServerURL); try { httpWebServices.ExecutePostRequest(); if(httpWebServices.getResponseCode() == 200) { DataHolder = httpWebServices.getResponse(); if(DataHolder != null) { JSONArray jsonArray = null; try { jsonArray = new JSONArray(DataHolder); JSONObject jsonObject; FruitNames fruitNames; fruitNamesList = new ArrayList<FruitNames>(); for(int i=0; i<jsonArray.length(); i++) { fruitNames = new FruitNames(); jsonObject = jsonArray.getJSONObject(i); fruitNames.Fruit_Name = jsonObject.getString("Fruit_Name"); fruitNamesList.add(fruitNames); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { Toast.makeText(context, httpWebServices.getErrorMessage(), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { progressBar.setVisibility(View.GONE); FruitsNameListView.setVisibility(View.VISIBLE); if(fruitNamesList != null) { ListViewAdapter adapter = new ListViewAdapter(fruitNamesList, context); FruitsNameListView.setAdapter(adapter); } } } }

Code for ListViewAdapter.java file.

package com.android_examples.json_listview_android_examplescom; /** * Created by Juned on 12/3/2017. */ import android.content.Context; import android.view.LayoutInflater; import android.widget.BaseAdapter; import android.widget.TextView; import android.view.View; import java.util.List; import android.app.Activity; import android.view.ViewGroup; public class ListViewAdapter extends BaseAdapter { Context ContextObj; List<FruitNames> TempList; public ListViewAdapter(List<FruitNames> listValue, Context context) { this.ContextObj = context; this.TempList = listValue; } @Override public int getCount() { return this.TempList.size(); } @Override public Object getItem(int position) { return this.TempList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewItem viewItem = null; if(convertView == null) { viewItem = new ViewItem(); LayoutInflater layoutInfiater = (LayoutInflater)this.ContextObj.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = layoutInfiater.inflate(R.layout.listview_items, null); viewItem.FruitNameTextView = (TextView)convertView.findViewById(R.id.textView1); convertView.setTag(viewItem); } else { viewItem = (ViewItem) convertView.getTag(); } viewItem.FruitNameTextView.setText(TempList.get(position).Fruit_Name); return convertView; } } class ViewItem { TextView FruitNameTextView; }

Code for HttpWebServices.java file.

package com.android_examples.json_listview_android_examplescom; /** * Created by Juned on 12/3/2017. */ import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; public class HttpWebServices {public int responseCode; public String message; public String response; public ArrayList<NameValuePair> ArrayListParams; public ArrayList <NameValuePair> headers; public String UrlHolder; public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public HttpWebServices(String url) { HttpWebServices.this.UrlHolder = url; ArrayListParams = new ArrayList<NameValuePair>(); headers = new ArrayList<NameValuePair>(); } public void AddParam(String name, String value) { ArrayListParams.add(new BasicNameValuePair(name, value)); } public void AddHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value)); } public void ExecuteGetRequest() throws Exception { String MixParams = ""; if(!ArrayListParams.isEmpty()) { MixParams += "?"; for(NameValuePair p : ArrayListParams) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8"); if(MixParams.length() > 1) { MixParams += "&" + paramString; } else { MixParams += paramString; } } } HttpGet httpGet = new HttpGet(UrlHolder + MixParams); for(NameValuePair h : headers) { httpGet.addHeader(h.getName(), h.getValue()); } executeRequest(httpGet, UrlHolder); } public void ExecutePostRequest() throws Exception { HttpPost httpPost = new HttpPost(UrlHolder); for(NameValuePair h : headers) { httpPost.addHeader(h.getName(), h.getValue()); } if(!ArrayListParams.isEmpty()) { httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8)); } executeRequest(httpPost, UrlHolder); } private void executeRequest(HttpUriRequest request, String url) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 10000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse httpResponse; try { httpResponse = httpClient.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); response = convertStreamToString(inputStream); inputStream.close(); } } catch (ClientProtocolException e) { httpClient.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { httpClient.getConnectionManager().shutdown(); e.printStackTrace(); } } private String convertStreamToString(InputStream is) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); StringBuilder stringBuilder = new StringBuilder(); String line = null; try { while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return stringBuilder.toString(); } }

Code for FruitNames.java file.

package com.android_examples.json_listview_android_examplescom; /** * Created by Juned on 12/3/2017. */ public class FruitNames { public String Fruit_Name ; public String getFruit_Name() { return Fruit_Name; } }

Code for activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?> <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" tools:context="com.android_examples.json_listview_android_examplescom.MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview1" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> </RelativeLayout>

Code for listview_items.xml layout file.

<?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"> <TextView android:id="@+id/textView1" android:text="Default Item Text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000" android:padding="7dp" android:textSize="22dp" /> </LinearLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android_examples.json_listview_android_examplescom"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Screenshots :

JSON Parsing Custom ListView

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...