I want to show logo from json but it doesn't work. Check my code and inform me about the bug. Else app name and description working fine. They only problem is that it now showing logo. Json is passing the link of that logo. I also use Glide but it doesn't work for me. I done all thing to fix it but i am unable for fix it. All code related to this is below. Please have a look at it
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class BrandshaperActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brandshaper);
new ParseTask().execute();
}
private class ParseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
#Override
protected String doInBackground(Void... params) {
try {
String $url_json = "https://myapi.ga";
URL url = new URL($url_json);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
Log.d("FOR_LOG", resultJson);
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
final ListView lView = (ListView) findViewById(R.id.lvMain);
String[] from = {"app_name","desc","app_logo"};
int[] to = {R.id.app_name,R.id.desc,R.id.app_logo};
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashmap;
try {
JSONObject json = new JSONObject(strJson);
JSONArray jArray = json.getJSONArray("offers");
for (int i = 0; i < jArray.length(); i++) {
JSONObject friend = jArray.getJSONObject(i);
String appname = friend.getString("name");
String description = friend.getString("description");
String applogo = friend.getString("icon");
Picasso.get().load(arrayList.get(position).getThumbnailUrl(applogo)).into(app);
hashmap = new HashMap<String, String>();
hashmap.put("app_name", "" + appname);
hashmap.put("desc", "" + description);
arrayList.add(hashmap);
}
final SimpleAdapter adapter = new SimpleAdapter(BrandshaperActivity.this, arrayList, R.layout.brandshaper_item,from , to);
lView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFF"
android:gravity="left">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_marginLeft="4dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/app_logo"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingStart="3dp"
android:src="#drawable/img_bigcash">
</ImageView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenirblack"
android:text="BigCash"
android:gravity="center"
android:textColor="#color/black"
android:textSize="18dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat_regular"
android:text="Install & Sign up to 200 coins"
android:gravity="center"
android:textColor="#color/black"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="end">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/arrow"></ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<ListView
android:id="#+id/lvMain"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</RelativeLayout>
Related
I'm trying to display read from table in database, what i have written so far passes the json, however rather than showing in textview - it displays as a short popup, and then disappears.
Activity_tasks.java
package com.example.myapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class activity_tasks extends AppCompatActivity {
TextView TextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button button = findViewById(R.id.button1);
button.setOnClickListener(v -> showInfo());
TextView = findViewById(R.id.textView4);
downloadJSON();
}
private void downloadJSON() {
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
setTextView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://myurl.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void setTextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
}
}
private void showInfo() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setIcon(R.drawable.alert);
builder.setTitle(" ");
builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");
// Create and show the AlertDialog
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
I have a funny feeling this is something about me having a button requesting a pop-up too in the code, perhaps I haven't integrated the 2nd onCreate properly?
The above is linked to a textview on activity_tasks.xml
Example on phone:
activity.xml below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
android:background="#color/black"
android:clickable="true"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:focusable="true">
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="95dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.946"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="#drawable/shortlogo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/button"
android:layout_width="158dp"
android:layout_height="153dp"
android:background="#drawable/circlebutton"
android:text="#string/hit_me_again"
android:textColor="#000"
android:textSize="8sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.896" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/alert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="183dp"
android:layout_height="119dp"
android:textColor="#color/white"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/design"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.092"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/version_0_0_1"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.963"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What you are seeing at the bottom is the toast you create in onPostExecute(). You receive the data, but then never update the text of the TextView. In setTextView() you could also do that:
textView.setText(json);
On another note: Don't use AsyncTasks anymore. They are deprecated and way too laborious. Also, to read the Json much more easily, you can use a library like Gson or Moshi.
I've been working on an app that uses a vertical RecyclerView inside a fragment, all inside a ViewPager2 object with a tabLayout. I can't seem to figure out how to make all these things work together. Currently, it looks like I got it to show the recycler view with the data but the tabs aren't showing up and the items in the list are spaced like they're different pages. Could someone explain how I'm messing up?
It looks like this:
I'd like it to be like this:
Here's the code so far:
Classes
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.Style;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox Access token
Mapbox.getInstance(getApplicationContext(), getString(R.string.mapbox_api_key));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(mapboxMap -> mapboxMap.setStyle(Style.DARK, style -> {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}));
ViewPager2 pager = findViewById(R.id.view_pager);
ViewPageAdapter pageAdapter = new ViewPageAdapter(getSupportFragmentManager(), getLifecycle());
pager.setAdapter(pageAdapter);
pager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
TabLayout tabLayout = findViewById(R.id.tabLayout2);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
new TabLayoutMediator(tabLayout, pager,
(tab, position) -> {
switch (position) {
case 0:
tab.setText(getString(R.string.stats_tab));
break;
case 1:
tab.setText(getString(R.string.news_tab));
break;
case 2:
tab.setText(getString(R.string.symptoms_tab));
break;
case 3:
tab.setText(getString(R.string.safety_tab));
break;
default:
break;
}
}).attach();
// Get data
new StatsLoader("https://api.covid19api.com/summary", pageAdapter, pager).execute();
}
}
StatsFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
public class StatsFragment extends Fragment {
View view;
RecyclerView recyclerView;
JSONArray covidData;
public StatsFragment(JSONArray data) {
covidData = data;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_page, container, false);
recyclerView = view.findViewById(R.id.recyclerView2);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(false);
RecyclerView.Adapter<CustomListAdapter.ListViewHolder> mAdapter = new CustomListAdapter(covidData);
recyclerView.setAdapter(mAdapter);
return view;
}
}
StatsLoader.java
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public class StatsLoader extends AsyncTask<String, Void, JSONArray> {
Exception exception;
String urlString = "";
static JSONArray covidData = new JSONArray();
ViewPageAdapter pageAdapter;
public StatsLoader(String url, ViewPageAdapter adapter) {
super();
urlString = url;
pageAdapter = adapter;
}
#Nullable
#Override
public JSONArray doInBackground(String ... urls) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
covidData = json.getJSONArray("Countries");
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i < covidData.length(); i++) {
list.add(covidData.get(i));
}
SortJsonArray sortJsonArray = new SortJsonArray();
sortJsonArray.sortArray(list, "TotalConfirmed", false);
covidData = new JSONArray();
for (Object object : list) {
covidData.put(object);
}
return covidData;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(JSONArray coviddata) {
if (this.exception == null) {
Log.d("Check", "Works!");
pageAdapter.addFragment(new StatsFragment(coviddata), "Stats");
}
}
}
Layouts
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:statusBarScrim="#null"
app:titleEnabled="false"
android:minHeight="?attr/actionBarSize" >
<fragment
android:id="#+id/mapView"
android:name="com.mapbox.mapboxsdk.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="350sp"
android:apiKey="#string/mapbox_api_key"
android:clickable="true"
android:enabled="true"
android:focusable="true"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginBottom="48dp"
android:gravity="top"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark"
app:title="" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/view_page" >
</androidx.viewpager2.widget.ViewPager2>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
view_page
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/list_view">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
list_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="14sp"
android:layout_margin="15sp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40sp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/name"
android:layout_toStartOf="#+id/name"
android:contentDescription="Image of country flag" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10sp" />
<TextView
android:id="#+id/cases"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
for tablayout :
take/make tablayout outside the CollapsingToolbarLayout
and for "list are spaced" :
make wrap_content height in view_page code
also list_view LinearLayout height to wrap_content
hope it helped :)
In your list_view , Use your parent layout height wrap_content not match_parent
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="14sp"
android:layout_margin="15sp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40sp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/name"
android:layout_toStartOf="#+id/name"
android:contentDescription="Image of country flag" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10sp" />
<TextView
android:id="#+id/cases"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
just wanna ask where to put the android.support.v4.widget.SwipeRefreshLayout on my codes? I'm confused if it should be on my activity_main.xml or in my list_item.xml file..
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And This is my List_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="#+id/datetime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:layout_weight="1" />
<TextView
android:id="#+id/qname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/qagent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/qevent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
</LinearLayout>
I Found some sample codes on the internet where they put it on the main xml but some samples also put it on the list xml..
This is my Main activity :
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
private static String IPaddress = "http://192.168.1.110/";
// URL to get contacts JSON
private static String url = IPaddress + "Projects/GetUsers.php";
private static final String TAG_QUEUE = "queue";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_NAME = "qname";
private static final String TAG_AGENT = "qagent";
private static final String TAG_EVENT = "qevent";
private static final String TAG_INFO1 = "info1";
private static final String TAG_INFO2 = "info2";
private static final String TAG_INFO3 = "info3";
// contacts JSONArray
JSONArray queue = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>>queueList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queueList = new ArrayList<HashMap<String, String>>();
// ListView lv = getListView();
// Calling async task to get json
new GetEventCounter().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetEventCounter extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity2.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
queue = jsonObj.getJSONArray(TAG_QUEUE);
for (int i = 0; i < queue.length(); i++) {
JSONObject c = queue.getJSONObject(i);
String datetime = String.format("%s : %s", TAG_DATETIME, c.getString(TAG_DATETIME));
String qname = String.format("%s : %s", TAG_NAME, c.getString(TAG_NAME));
String qagent = String.format("%s : %s", TAG_AGENT, c.getString(TAG_AGENT));
String qevent = String.format("%s : %s", TAG_EVENT, c.getString(TAG_EVENT));
String info1 = String.format("%s : %s", TAG_INFO1, c.getString(TAG_INFO1));
String info2 = String.format("%s : %s", TAG_INFO2, c.getString(TAG_INFO2));
String info3 = String.format("%s : %s", TAG_INFO3, c.getString(TAG_INFO3));
HashMap<String, String> event = new HashMap<String, String>();
event.put(TAG_DATETIME, datetime);
event.put(TAG_NAME, qname);
event.put(TAG_AGENT, qagent);
event.put(TAG_EVENT, qevent);
event.put(TAG_INFO1, info1);
event.put(TAG_INFO2, info2);
event.put(TAG_INFO3, info3);
queueList.add(event);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity2.this, queueList,
R.layout.list_item, new String[] { TAG_DATETIME, TAG_NAME, TAG_AGENT, TAG_EVENT, TAG_INFO1, TAG_INFO2, TAG_INFO3},
new int[] { R.id.datetime, R.id.qname, R.id.qagent, R.id.qevent, R.id.info1, R.id.info2, R.id.info3 });
setListAdapter(adapter);
}
}
protected Fragment getSampleFragment() {
// TODO Auto-generated method stub
return null;
}
}
This will be the output that i want to have an SwipeRefresh effect..
Those output came from MySQL Database :
This samples caused my confusion
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swype"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
And :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swype"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/serial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="25dp"
android:layout_margin="5dp"
android:layout_alignParentLeft="true"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/title"
android:layout_toRightOf="#id/serial"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:paddingLeft="20dp"
android:textSize="18dp" />
</RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Thanks!
To add the swipe to refresh widget to an existing app, add SwipeRefreshLayout as the parent of a single ListView or GridView. Remember that SwipeRefreshLayout only supports a single ListView or GridView child. - Add the SwipeRefreshLayout Widget
So, your activity_main.xml should be like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout
</LinearLayout>
Implementation:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
//to change the color of the refresh indictor
swipeRefreshLayout.setColorScheme(getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor));
}
#Override
public void onRefresh() {
//do something here
//setRefreshing(false) will hide the indicator
swipeRefreshLayout.setRefreshing(false);
}
}
It should wrap around the listview, something like this:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp">
<android.widget.ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.widget.ListView>
</android.support.v4.widget.SwipeRefreshLayout>
If you're using Android Studio, you can look at a Swiperefresh sample:
File\New\Import Sample\ then search for "swipe..."
In your java code, you initialize the SwipeRefresh object exactly how you would do a TextView, Button or anything else, except in your onResume(), you also want to put something like this:
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initiateRefresh();
}
});
and then inside initiateRefresh(), you do something like:
AssignData2ListView();
mSwipeRefreshLayout.setRefreshing(false);
I'm going to create a simple register form app that when user insert their username and password, EditText in UI shows the id of their record in database.
My app insert users into database correctly and show JSON output into EditText.
For Example when I insert first user to my database, EditText show this:
{
"id": "1", "0":"1"
}
But, I want show this in EditText:
1 instead of
{
"id" : "1", "0" : "1"
}
activity_main.xml
<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="#00aeef"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="18dp"
android:text="Register Example"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_username"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/edt_result"
android:layout_below="#+id/edt_password"
android:layout_marginTop="16dp"
android:background="#ffffff"
android:text="Insert"
android:textColor="#00aeef" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/edt_username"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_password"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/edt_username"
android:layout_below="#+id/textView2"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
<EditText
android:id="#+id/edt_result"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/btn_insert"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
</RelativeLayout>
InsertClass.java
package com.example.testphp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class InsertClass extends AsyncTask<String, Void, String>{
private Context context;
private ProgressDialog pDialog;
private EditText edt;
private String json = "";
private JSONObject jObj = null;
public InsertClass(Context context, EditText edt)
{
this.context = context;
pDialog = new ProgressDialog(context);
this.edt = edt;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading... Please wait");
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
try
{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2:8020/test/test.php";
String data = URLEncoder.encode("username","utf-8") +
"=" + URLEncoder.encode(username,"utf-8");
data += "&" + URLEncoder.encode("password","utf-8") +
"=" + URLEncoder.encode(password,"utf-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
json = sb.toString();
jObj = new JSONObject(json);
return sb.toString();
}
catch(JSONExeption e)
{
return new String("Exeption: " + e.getMessage());
}
catch(Exception e)
{
return new String("Exeption: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
try
{
edt.setText(jObj.getString("id"));
}
catch (JSONExeption e)
{ e.printStackTrace(); }
}
}
MainActivity.java
package com.example.testphp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
String username;
String password;
EditText edtUsername;
EditText edtPassword;
EditText edtResult;
Button btnInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsert = (Button) findViewById(R.id.btn_insert);
edtPassword = (EditText) findViewById(R.id.edt_password);
edtUsername = (EditText) findViewById(R.id.edt_username);
edtResult = (EditText) findViewById(R.id.edt_result);
btnInsert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edtUsername.getText().toString();
password = edtPassword.getText().toString();
new InsertClass(MainActivity.this, edtResult).execute(username,password);
}
});
}
#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;
}
}
test.PHP
<?php
$con = mysqli_connect("localhost" , "root" , "","test");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES '$username','$password')") or die(mysqli_query($con));
if($result)
{
$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = '$username'") or die(mysqli_query($con));
if($id_result)
{
$id_result = mysqli_fetch_array($id_result);
$response = array("id" => $id_result);
echo json_encode($response);
}
}
mysqli_close($con);
?>
Any suggestion, would be appreciated ...
Your response from PHP for user id=17 is {"id":{"0":"17","id":"17"}}
Try to change in php script
//$response = array("id" => $id_result);
$response["id"] = $id_result["id"];
then your rsponse will be {"id":"17"}
In your class InsertClass and function doInBackground() where you are converting result string to JsonObject like
json = sb.toString();
jObj = new JSONObject(json);
Add code:
String result = jObj.getString ("id");
Return result;
I have a class viewroom.java, to list all the rooms' title from database, as follows:
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
//import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class viewroom extends ListActivity {
// url to make request
private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";
// JSON Node names
private static final String TAG_ROOM = "room";
// private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
private static final String TAG_LOCATION = "location";
private static final String TAG_TITLE = "title";
private static final String TAG_QUANTITY = "quantity";
private static final String TAG_PRICE = "price";
private static final String TAG_CONTACT = "contact";
private static final String TAG_AREA = "area";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ADDRESS = "address";
// contacts JSONArray
JSONArray room = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_room);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
try {
// Getting Array of Contacts
room = json.getJSONArray(TAG_ROOM);
// looping through All Contacts
for(int i = 0; i < room.length(); i++){
JSONObject c = room.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String location = c.getString(TAG_LOCATION);
String quantity = c.getString(TAG_QUANTITY);
String address = c.getString(TAG_ADDRESS);
String price = c.getString(TAG_PRICE);
String contact = c.getString(TAG_CONTACT);
String area = c.getString(TAG_AREA);
String description = c.getString(TAG_DESCRIPTION);
String title = c.getString(TAG_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LOCATION, location);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_ADDRESS, address);
map.put(TAG_PRICE, price);
map.put(TAG_CONTACT, contact);
map.put(TAG_AREA, area);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
roomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
R.id.title, R.id.location, R.id.price });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
String price = ((TextView) view.findViewById(R.id.price)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_PRICE, price);
startActivity(in);
}
});
}
}
when one of those list item is clicked, details are shown in single Room Activity class. it
is as follows:
package com.iwantnew.www;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleRoomActivity extends Activity {
private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_room);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String location = in.getStringExtra(TAG_LOCATION);
String price = in.getStringExtra(TAG_PRICE);
// Displaying all values on the screen
TextView lblTitle = (TextView) findViewById(R.id.title_label);
TextView lblLocation = (TextView) findViewById(R.id.location_label);
TextView lblPrice = (TextView) findViewById(R.id.price_label);
lblTitle.setText(title);
lblLocation.setText(location);
lblPrice.setText(price);
}
}
there remains a big gap between each items in view room activity class, when all details are shown in single room activity.
and when list adapter is modified to
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
in view room activity, the gap vanishes but, single room activity does not show all the description.
in case you need my xml files:
view_room.xml
<?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:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/searchBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/slogan"
android:text="#string/Search" />
<EditText
android:id="#+id/searchArea"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/searchBtn"
android:ems="10"
android:hint="#string/hint"
android:inputType="text" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/slogan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/searchArea"
android:layout_below="#+id/brand"
android:text="#string/slogan"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic"
android:typeface="normal" />
<TextView
android:id="#+id/brand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/iWant"
android:textSize="#dimen/iwant" />
<Button
android:id="#+id/postBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="26dp"
android:text="#string/post" />
<TextView
android:id="#+id/room_list_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchBtn"
android:text="#string/room_list_heading"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic"
android:typeface="normal" />
<ListView
android:id="#android:id/list"
android:layout_below="#+id/room_list_heading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
single room.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Name Label -->
<TextView android:id="#+id/title_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<!-- Description Label -->
<TextView android:id="#+id/quantity_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/location_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
<TextView android:id="#+id/price_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<TextView android:id="#+id/contact_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/description_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
<TextView android:id="#+id/area_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<TextView android:id="#+id/address_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
list_room.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Name Label -->
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="#+id/location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/contact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/area"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
</LinearLayout>
I want to vanish gap in the first picture and still get the second picture as it is.