adapter not set in the listview android - android

Hi I am working on the list view, I just want to set the values in the listview. I posted the code as below.As per SimpleAdapter It just shows the name of the content .I want to display the count also.But the count does not displayed and in the app it only shows name of the textview instead of the count. Please suggest me solution for the problem.I also attached the screenshot.
import java.util.ArrayList;
import android.R.*;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Folders extends navigation_drawer_class {
static final String NEW = "new", OVERDUE = "overdue", ASSIGNED = "assigned", TRASH = "trash", SPAM = "spam", NAME = "name", COUNT = "count";
ListView folders_list;
String[] folders;
String[] filter_id = {
"2",
"3",
"4",
"5",
"6"
};
List < String > folder_count;
JSONArray quick_view_array;
JSONObject quick_view_obj, count_obj;
String new_count, overdue_count, assigned_count, trash_count, spam_count;
List < HashMap < String, String >> menuItems;
Dialog dialog;
String URL;
Operation op = new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.folders);
new getbrand().execute();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//-----------------------
getLayoutInflater().inflate(R.layout.folders, frameLayout);
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
//------------------------
if (Operation.isNetworkAvailable(this)) {
folders_list = (ListView) findViewById(R.id.folder_display_list);
new folders().execute();
folders_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
// TODO Auto-generated method stub
String fid = filter_id[position];
String title = folders[position];
Intent i = new Intent(Folders.this, Tickets.class);
i.putExtra("filter_id", "&vis_filter_id=" + fid);
i.putExtra("title", title);
i.putExtra("set_queue", "no");
startActivity(i);
}
});
} else {
Operation.showToast(getApplicationContext(), R.string.no_network);
}
}
private class folders extends AsyncTask < Void, Void, JSONArray > {
Dialog dialog;
#Override
public void onPreExecute() {
dialog = new Dialog(Folders.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void...params) {
// TODO Auto-generated method stub
URL = op.getUrl(getApplicationContext(), "ticket", "quick_view", "");
quick_view_array = JSONfunctions.getJSONfromURL(URL + "&vis_encode=json", Folders.this);
return quick_view_array;
}
#Override
public void onPostExecute(JSONArray quick_view_array) {
super.onPostExecute(quick_view_array);
try {
quick_view_obj = quick_view_array.getJSONObject(0);
count_obj = quick_view_obj.getJSONObject("count");
folder_count = new ArrayList < String > ();
folder_count.add(count_obj.getString(NEW));
folder_count.add(count_obj.getString(OVERDUE));
folder_count.add(count_obj.getString(ASSIGNED));
folder_count.add(count_obj.getString(TRASH));
folder_count.add(count_obj.getString(SPAM));
folders = getResources().getStringArray(R.array.folders);
menuItems = new ArrayList < HashMap < String, String >> ();
for (int i = 0; i < filter_id.length; i++) {
HashMap < String, String > map = new HashMap < String, String > ();
map.put(NAME, folders[i]);
map.put(COUNT, folder_count.get(i));
menuItems.add(map);
}
SimpleAdapter list = new SimpleAdapter(Folders.this,
menuItems,
R.layout.folders,
new String[] {
NAME,
COUNT
},
new int[] {
R.id.folder_name, R.id.folder_count
}
);
folders_list.setAdapter(list);
dialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String filter_id = null, Tickets_title = null;
int start_limit = 0, page_no = 1;
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_inbox:
Intent inbox = new Intent(Folders.this, Tickets.class);
inbox.putExtra("filter_id", "&vis_filter_id=1");
inbox.putExtra("title", "Inbox");
inbox.putExtra("set_queue", "no");
startActivity(inbox);
return true;
case R.id.menu_new_ticket:
Intent new_ticket = new Intent(Folders.this, New_Ticket_step1.class);
startActivity(new_ticket);
return true;
case R.id.menu_ticket_queue:
Intent ticket_queue = new Intent(Folders.this, Queues.class);
ticket_queue.putExtra("set_queue", "set");
startActivity(ticket_queue);
return true;
case R.id.menu_clients:
Intent clients = new Intent(Folders.this, Client.class);
startActivity(clients);
return true;
/* case R.id.menu_blabby:
Intent blabby = new Intent(Folders.this,Blabby.class);
blabby.putExtra("operation","get_blabs");
blabby.putExtra("filter","");
blabby.putExtra("title",(String)getString(R.string.blabs));
startActivity(blabby);
return true; */
//-------- Added for separate page
case R.id.menu_pin:
Intent pin = new Intent(Folders.this, Pinned_items.class);
startActivity(pin);
return true;
//-------- Added for separate page
case R.id.menu_settings:
Intent settings = new Intent(Folders.this, Settings.class);
startActivity(settings);
return true;
case R.id.menu_ticket_search:
Intent search = new Intent(Folders.this, Search.class);
search.putExtra("set_queue", "no");
startActivity(search);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
private class getbrand extends AsyncTask < Void, Void, JSONArray > {
Dialog dialog;
#Override
public void onPreExecute() {
dialog = new Dialog(Folders.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void...params) {
// TODO Auto-generated method stub
String access = op.getUrl(getApplicationContext(), "ticket", "get_branding", "");
JSONArray access_denied = JSONfunctions.getJSONfromURL(access + "&vis_encode=json", Folders.this);
return access_denied;
}
#Override
public void onPostExecute(JSONArray access_denied) {
super.onPostExecute(access_denied);
String access_result = access_denied.toString();
ActionBar ab = getActionBar();
if (access_result.equals("[\"1\"]")) {
ab.setTitle(R.string.app_name);
ab.setIcon(R.drawable.application_icon);
// ab.setDisplayShowTitleEnabled(false);
// ab.setDisplayShowHomeEnabled(false);
// ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
} else {
ab.setTitle(R.string.nobrand_app_name);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
ab.setIcon(R.drawable.white3);
}
dialog.dismiss();
}
}
}
XML:
<?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"
android:orientation="horizontal"
android:padding="3dp"
android:weightSum="100">
<TextView
android:id="#+id/folder_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="30"
android:text="TextView"
android:textColor="#115c28"
android:textSize="15dp" />
<TextView
android:id="#+id/folder_count"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginRight="10dp"
android:layout_weight="70"
android:gravity="center"
android:text="0"
android:textColor="#115c28"
android:textSize="20dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="vertical">
<ListView
android:id="#+id/folder_display_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="3dp"
android:weightSum="100">
<TextView
android:id="#+id/folder_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
The first textview takes up the full width of the horizontal LinearLayout so you can't see the second textview.
You can see the count by making the width of the textviews wrap_content but it probably won't match the design you're trying to achieve.

Hi i just chage the xml template as follows.
<?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"
android:layout_gravity="top"
android:orientation="vertical"
android:weightSum="100"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- -->
<TextView
android:id="#+id/folder_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="30dip"
android:textSize="15dp"
android:layout_weight="1"
android:textColor="#115c28"/>
<TextView
android:id="#+id/folder_count"
android:layout_width="0dp"
android:layout_height="60dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#115c28"
android:gravity="center"
android:paddingRight="30dip"
android:paddingLeft="35dip"
android:layout_weight="1" />
<!-- -->
</LinearLayout>
<ListView
android:id="#+id/folder_display_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Its working properly now.

Related

Spinner item selection problem with TextView [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a table in Mysql database with some plugs, and i added all the plugs to spinner from database.I want to retreive the data according to spinner selection.I am facing a problem that there is two records in database for plug1,when i selected plug1 its retreiving properly,when i selected plug2 in spinner its retreiving another record of plug1. I have used on-selected item position that is why it is taking position wise order.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".DashboardActivity"
android:orientation="vertical"
android:background=" #dfe3e7"
tools:showIn="#layout/app_bar_dashboard">
<Spinner
android:id="#+id/spinnerDevices"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:background="#drawable/spinner"
android:layout_marginTop="20dp"
android:overlapAnchor="false"></Spinner>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif"
android:text="ON/OFF"
android:textSize="20sp"
android:paddingLeft="5dp"/>
<Switch
android:id="#+id/on"
android:layout_width="100dp"
android:layout_height="45dp"
android:checkable="true"
android:padding="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="15dp"
>
<android.support.v7.widget.CardView
android:layout_width="130dp"
android:layout_height="180dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background=" #1c2833"
android:padding="8dp">
<ImageView
android:id="#+id/imageView1"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/image1"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/device1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView1"
android:layout_marginTop="10dp"
android:layout_marginLeft="1dp"
android:fontFamily="serif"
android:text="TEMPERATURE"
android:textColor="#fff"
android:textSize="15sp" />
<TextView
android:id="#+id/meter1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/device1"
android:fontFamily="serif"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:textColor="#ff6861"
android:textSize="30sp"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="130dp"
android:layout_height="180dp"
android:layout_margin="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background=" #1c2833"
android:padding="7dp">
<ImageView
android:id="#+id/imageView2"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/image2"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/device2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView2"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:fontFamily="serif"
android:textColor="#fff"
android:text="CURRENT"
android:textSize="15sp" />
<TextView
android:id="#+id/meter2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/device2"
android:fontFamily="serif"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:textColor="#ff6861"
android:textSize="30sp"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="130dp"
android:layout_height="180dp"
android:layout_margin="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background=" #1c2833"
android:padding="7dp">
<ImageView
android:id="#+id/imageView3"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/image3"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/device3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView3"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:fontFamily="serif"
android:text="VOLTAGE"
android:textColor="#fff"
android:textSize="15sp" />
<TextView
android:id="#+id/meter3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/device3"
android:fontFamily="serif"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:textSize="30sp"
android:textColor="#ff6861"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>>
</LinearLayout
JAVA
package com.example.sp;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DashboardActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener , NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "DashboardActivity";
private String URLstring = "http://192.168.0.108/Smart/getdata.php";
public static final String JSON_ARRAY = "data";
public static final String EmployeeNamearray = "plugno";
private TextView textView;
String line=null;
private ArrayList<String> names = new ArrayList<String>();
private JSONArray data;
private JSONArray result;
private ArrayList<String> students;
private final int jsoncode = 1;
private Spinner spinner;
String status="";
private TextView textViewName, textViewCourse, textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.greeting_text_view);
spinner = (Spinner) findViewById(R.id.spinnerDevices);
names = new ArrayList<String>();
students = new ArrayList<String>();
getdata();
getData();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
textViewName = (TextView) findViewById(R.id.meter1);
textViewCourse = (TextView) findViewById(R.id.meter2);
textViewSession = (TextView) findViewById(R.id.meter3);
spinner.setOnItemSelectedListener(this);
Switch s = (Switch) findViewById(R.id.on);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(DashboardActivity.this, "switch is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DashboardActivity.this, "switch is off", Toast.LENGTH_SHORT).show();
}
}
});
}
private void getData() {
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
if(json.getString("plugno").equals("plugno")){
students.add(json.getString(Config.TAG_PLUGNO));
}
//Adding the name of the student to array list
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(DashboardActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
spinner.setAdapter(new ArrayAdapter<String>(DashboardActivity.this, android.R.layout.simple_spinner_dropdown_item, names));
}
//Method to get student name of a particular position
private String getName(int position) {
String name = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_TEMPERATURE);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position) {
String course = "";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_CURRENT);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position) {
String session = "";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_VOLTAGE);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
private void getdata() {
StringRequest stringRequest = new StringRequest("http://192.168.0.108/Smart/getdata.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
data = j.getJSONArray(JSON_ARRAY);
empdetails(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void empdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
names.add(json.getString(EmployeeNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
// arrayList.add(0,"Select Employee");
spinner.setAdapter(new ArrayAdapter<String>(DashboardActivity.this, android.R.layout.simple_spinner_dropdown_item,names));
spinner.setAdapter(new ArrayAdapter<String>(DashboardActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position+
#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) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent i = new Intent(getApplicationContext(), AddPlugActivity.class);
startActivity(i);
// Handle the camera action
} else if (id == R.id.nav_manage) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
In this method add like this
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
yourlist.get(position);
}
Let me know if it works for you .

Unable to set ListView Divider color in Android

I have an activity with a ListView in it. I have set the color of ListView divider to black using android:divider="#000000" attribute and set the divider height to 1dp. For some reason the divider line is showing blue color instead of black. Here is my xml. Any help will be appreciated.
second_selection.xml
<LinearLayout 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="#1A1A1A"
android:orientation="vertical"
tools:context="com.example.saregama.MainActivity" >
<FrameLayout
android:id="#+id/myframe"
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#000000" />
<include
android:id="#+id/new_tool"
layout="#layout/toolbar_actionbar_with_headerbar" />
<ImageView
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:src="#drawable/newloading" />
<ListView
android:id="#+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1dp"
android:layoutAnimation="#anim/layout_bottom_to_top_slide"
android:padding="10dp"
android:text="#string/hello_world" />
</LinearLayout>
And if necessary here is my code
SecondSelection.java
package com.example.something;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class SecondSelection extends ActionBarActivity {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<String> records;
Intent i;
Intent j;
Intent k;
private Toolbar toolbar;
ValueAnimator colorAnimation;
FrameLayout myframe;
ValueAnimator statusAnim;
ImageView image;
Animation anim;
BackTask bt;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_selection);
toolbar = (Toolbar) findViewById(R.id.new_tool);
setSupportActionBar(toolbar);
myframe = (FrameLayout)findViewById(R.id.myframe);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else{
myframe.setVisibility(View.GONE);
}
context = this;
records = new ArrayList<String>();
listProduct = (ListView) findViewById(R.id.product_list);
image = (ImageView)findViewById(R.id.loader);
anim = AnimationUtils.loadAnimation(this, R.anim.myanim);
image.startAnimation(anim);
i = new Intent(this, ReportActivity.class);
j = new Intent(this, RequestActivity.class);
k = new Intent(this, AboutDeveloper.class);
bt = new BackTask();
bt.execute();
adapter = new CustomAdapter(context, R.layout.list_item_second,
R.id.pro_name, records);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
String sText = ((TextView) v.findViewById(R.id.pro_name))
.getText().toString();
Intent songIntent = new Intent(getApplicationContext(),
MainActivity.class);
songIntent.putExtra("second_selection", sText);
startActivity(songIntent);
}
});
//Animation for Action Bar
Integer colorFrom = getResources().getColor(R.color.first);
Integer colorTo = getResources().getColor(R.color.last);
colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
toolbar.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Animation for Status Bar
Integer colorFirst = getResources().getColor(R.color.begin);
Integer colorLast = getResources().getColor(R.color.end);
statusAnim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFirst, colorLast);
statusAnim.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
myframe.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Start the Animations after fetching the list.
//After executing the bt.execute()
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
}
return super.onKeyDown(keyCode, event);
}
#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();
return super.onOptionsItemSelected(item);
}
#Override
public void onStart()
{
super.onStart();
if (bt.getStatus() == Status.FINISHED) {
doAnimation();
}
}
private void doAnimation() {
statusAnim.setDuration(800);
colorAnimation.setDuration(1300);
colorAnimation.start();
statusAnim.start(); // start animations
}
// background process to make a request to server and list product
// information
private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// pd = new ProgressDialog(context);
// pd.setTitle("Retrieving data");
// pd.setMessage("Please wait.");
// pd.setCancelable(true);
// pd.setIndeterminate(true);
// pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
records.clear();
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String record = json_data.getString("alp") + "__"
+ json_data.getString("f");
records.add(record);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null)
// pd.dismiss(); // close dialog
image.clearAnimation();
image.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
doAnimation();// notify the ListView to get new
// records
}
}
}
Update:
This problem persists only in devices having API < 19
if nothing works, then u can create your own divider.
First remove the default divider.
android:dividerHeight="0dp"
android:divider="#null"
And then add the view in your custom_row_layout.xml
`
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="30dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:textSize="17sp"
android:textColor="#color/white" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white" />
</LinearLayout>
`
I set up a style for ListViews, in my styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
...
<style name="ListViews" parent="#android:style/Widget.ListView">
<item name="android:cacheColorHint">#color/transparent</item>
<item name="android:divider">#drawable/list_divider</item>
<item name="android:dividerHeight">1px</item>
</style>
...
</resources>
My ListView uses that style as such:
style="#style/ListViews"
Obviously, I have such drawable in my drawable folder.
My list_divider.xml drawable is as such:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#color/navy_semi" />
</shape>
[EDIT]
Obviously, instead of #color/transparent and #color/navy_semi, use your own colors.
These ones are defined only in my color resurces.
Use android:background instead of android:divider
<LinearLayout 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="#1A1A1A"
android:orientation="vertical"
tools:context="com.example.saregama.MainActivity" >
<FrameLayout
android:id="#+id/myframe"
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#000000" />
<include
android:id="#+id/new_tool"
layout="#layout/toolbar_actionbar_with_headerbar" />
<ImageView
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:src="#drawable/newloading" />
<ListView
android:id="#+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1dp"
android:layoutAnimation="#anim/layout_bottom_to_top_slide"
android:padding="10dp"
android:text="#string/hello_world" />
use below attribute in your list view.
android:cacheColorHint="#null"

OnItemClickListener stops working when ListActvity called inside layout from another layout file

I could not frame a proper question but here is what I am facing. I have a ListActvity and here's the code:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class dbMainactivty extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
private TextView text;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.setScreenName("dbMainactivty");
t.send(new HitBuilders.AppViewBuilder().build());
// Locate ListView
noteListView = getListView();
// setContentView(R.layout.list_note);
//noteListView = (ListView) findViewById(R.id.listview);
setContentView(R.layout.dbmainactivitylayout);
text = (TextView) findViewById(R.id.mainText);
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[] { TITLE };
int[] to = new int[] { R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(dbMainactivty.this,
R.layout.list_note, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(dbMainactivty.this, ViewNote.class);
// Pass the ROW_ID to ViewNote activity
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStop(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
//return true;
return super.onCreateOptionsMenu(menu);
}
//#Override
//public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
//
// if (drawerListener.onOptionsItemSelected(item)) {
// return true;
// }
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
// Intent ia = new Intent(Intent.ACTION_VIEW);
// ia.setData(Uri.parse("market://details?id=" + getApplicationContext().getPackageName()));
// startActivity(i);
//break;
String webpage = "http://developer.android.com/index.html";
Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent2);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.send(new HitBuilders.EventBuilder()
.setCategory("rate CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "");
i.setType("text/plain");
startActivity(i);
Tracker t1 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t1.send(new HitBuilders.EventBuilder()
.setCategory("share CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
return true;
case R.id.action_maila:
Intent imail = new Intent(Intent.ACTION_SEND);
imail.setType("message/rfc822");
imail.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
imail.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
imail.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(imail, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(dbMainactivty.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t2 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t2.send(new HitBuilders.EventBuilder()
.setCategory("Mail CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
break;
case R.id.action_home:
Intent ihome = new Intent(this, MainActivity.class);
startActivity(ihome);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t3 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t3.send(new HitBuilders.EventBuilder()
.setCategory("GoToHome CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
return true;
}
return super.onOptionsItemSelected(item);
};
// GetNotes AsyncTask
private class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(dbMainactivty.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes("maincat LIKE 'quiz' AND subcat LIKE 'test'");
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
Cursor cursor = noteAdapter.getCursor();
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
//do your action
//Fetch your data
// GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
//Toast.makeText(getBaseContext(), "Yipeee!", Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(dbMainactivty.this, "No records yet!", Toast.LENGTH_SHORT);
toast.show();
toast.setGravity(Gravity.CENTER, 0, 0);
finish();
}
dbConnector.close();
}
}
#Override
protected void onStart() {
super.onStart();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Please check your Internet Connection.")
.setTitle("")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
}
}
Now the layout file for this is list_note.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.96"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/ViewTitleNotes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:textColor="#000000"
android:textStyle="bold"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
When I implement above code every thing works fine. However, I want to include some other data so i am calling another layout file which includes additional data:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/mainText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pinned Questions" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#FFFFFF"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:text="There is no data"
android:textStyle="bold" />
</RelativeLayout>
When I include this layout the list shows up but nothing happens when I click on list item. The normal working would be when I click list item it should open the next activity with desired clicked item.
Thanks in advance.
Well I would suggest You To Implement View.OnItemClickListener() and then use
noteListView.setOnItemClickListener(this);
This will work perfectly.
Hope I Helped.

Title not changed when running android application

I have made an application in android,now i have made activities notes.xml,contactinfo.xml and an android xml file named listplaceholder5.xml,i need is i've changed the android:text of textview to "notes"in "listplaceholder5.xml" file which is used in note.java but it ,not displaying "notes" its displaying "contact".i have tried sode a sbelow:please help me to change the code so that i can solve it,
Note.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"
>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="item_title"
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<!--
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="#string/hello"
android:visibility="gone"
/>-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone : "
android:textColor="#000000"
android:textSize="14sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item_subtitle"
android:textColor="#000000"
android:textSize="14sp"
/>
<TextView
android:id="#+id/item_subtitle1"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="14sp"
android:layout_width="wrap_content"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
<!-- New Layout -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:paddingRight="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/forward" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listplaceholder5.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/detailpage">
<LinearLayout android:layout_width="fill_parent"
android:weightSum="1"
android:background="#drawable/bottombackground"
android:id="#+id/linearLayout1"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_marginLeft="18dp"
android:layout_weight="0.88"
android:textSize="18sp"
android:textStyle="bold"
android:id="#+id/textView1"
android:text="Notes"
android:gravity="center"
android:layout_gravity="center"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:layout_width="fill_parent"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"
android:listSelector="#drawable/list_selector"
/>
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
</LinearLayout>
NOteActivity.java
package com.hussain.realtylog;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hussain.realtylog.Contact.DownloadWebPageTask;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class NoteActivity extends ListActivity {
JSONArray jArray = null;
JSONObject json_data = null;
String getMLSID =null;
TextView titl;
// Button btnBuyer;
// Button btnRental;
String getJson =null;
public String user=null;
public static String urlContact=null;
public static String jsonContact=null;
ArrayList<HashMap<String, String>> mylist;
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected String doInBackground(String... urls) {
user= TabBarExample.getJsonUser;
urlContact = StoreSession.strBaseURL+"&username="+user+"&act=ContactList";
if( StoreSession.FlagContact == 0){
boolean isNet = checkInternetConnection();
if(isNet==true){
jsonContact = JSONfunctions.getJSONfromURL(urlContact);
}else{
alertbox("Contact", "Please check your mobile network setting and try again.");
}
}
mylist = new ArrayList<HashMap<String, String>>();
try{
jArray = new JSONArray(jsonContact);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("ID", e.getString("ID"));
map.put("username", e.getString("username"));
map.put("email", e.getString("email"));
map.put("phone", e.getString("phone"));
map.put("phone2", e.getString("phone2"));
map.put("fullname", e.getString("fullname"));
map.put("address", e.getString("address"));
map.put("notes", e.getString("info"));
map.put("active", e.getString("active"));
map.put("created", e.getString("created"));
map.put("lastUpdate", e.getString("lastUpdate"));
map.put("guest", e.getString("guest"));
map.put("category", "Category: "+e.getString("category"));
mylist.add(map);
}
}catch(JSONException e){
// Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListAdapter adapter = new SimpleAdapter(NoteActivity.this, mylist , R.layout.activity_note,
new String[] { "fullname", "phone" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
int[] colors = {0, 0xFFFF0000, 0}; // red for the example
lv.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
lv.setDividerHeight(1);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final ProgressDialog dialog = ProgressDialog.show(NoteActivity.this, "Loading",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
#SuppressWarnings("unchecked")
public void run() {
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
final String strName= o.get("fullname").toString();
final String strEmail= o.get("email").toString();
final String Phone= o.get("phone").toString();
final String Phone2= o.get("phone2").toString();
getMLSID = o.get("notes").toString();
Intent newActivityFirst = new Intent(NoteActivity.this, ContactInfo.class);
newActivityFirst.putExtra("name", strName);
newActivityFirst.putExtra("strEmail", strEmail);
newActivityFirst.putExtra("phone", Phone);
newActivityFirst.putExtra("phone2", Phone2);
newActivityFirst.putExtra("notes", getMLSID);
NoteActivity.this.startActivity(newActivityFirst);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
});
StoreSession.FlagContact=1;
//dialog.hide();
dialog.dismiss();
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected void onPreExecute() {
dialog = new ProgressDialog(NoteActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Please wait...");
dialog.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
setContentView(R.layout.listplaceholder5);
TextView title=(TextView)findViewById(R.id.textView1);
title.setText("Notes");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
StoreSession.FlagListing =0;
StoreSession.FlagBuyer =0;
StoreSession.FlagRental =0;
StoreSession.FlagDocument =0;
StoreSession.FlagContact =0;
ActiveShowingInfo.flagActiveClickCheck =0;
Main.username.setText("");
Main.pwd.setText("");
return false;
}
return super.onKeyDown(keyCode, event);
}
protected void alertbox(String title, String mymessage)
{
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
})
.show();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("tag", "Internet Connection Not Present");
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_note, menu);
return true;
}
}
please help me to solve this problem.thanking you in advance.
after getting the title as follows:
title= (TextView) findViewById(R.id.item_title);
use setText method to set the title as you wish.
I think it will solve your problem.

nulPointException on button

i need to be able to make calls from an activity. so here is a my activity that shows details of people and i have a call button. but i get a nullPointerError when i call the setOnClickListener(...). why? thnks for any help.
package com.AndroidApp.pagine;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.AndroidApp.ApplicationController;
import com.AndroidApp.R;
import com.AndroidApp.XMLFunctions;
import com.AndroidApp.Login.LoginActivity;
import com.AndroidApp.domain.Anagrafica;
public class DettagliPagina extends ListActivity {
public Anagrafica anagrafica;
public ArrayList<HashMap<String, String>> mylist;
private boolean paused, newIntentSelected = false;
private ProgressDialog progressDialog;
private SharedPreferences mPreferences;
public ApplicationController ac;
private Button bCall;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ac = (ApplicationController)getApplication();
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String nome = mPreferences.getString("nome", "Errore");
String cognome = mPreferences.getString("cognome", "Errore");
setTitle("Sessione di : " + nome + " " + cognome);
new BackgroundAsyncTask().execute();
}
#Override
protected void onStart() {
super.onStart();
bCall = (Button) findViewById(R.id.bCall);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
// add button listener
bCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:3492395504"));
startActivity(callIntent);
}
});
}
#Override
protected void onPause() {
super.onPause();
paused = true;
ac.setOraAttuale(Calendar.getInstance());
ac.oraAttuale.add(Calendar.MINUTE, 1);
ac.setOraScadenza(ac.getOraAttuale());
Log.d("DettagliPAgina scadenza", ac.getOraScadenza().getTime().toString());
}
#Override
protected void onResume() {
super.onResume();
if (ac.isKill) {
finish();
}
if (paused && !newIntentSelected){
if (Calendar.getInstance().after(ac.getOraScadenza())){
//torna al login con toast sessione scaduta
ac.setSessioneTerminata(true);
Toast.makeText(getApplicationContext(), "Sessione Scaduta", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DettagliPagina.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
public class BackgroundAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... paths) {
mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLFunctions.getXML();
Document doc = XMLFunctions.xmlFromString(xml);
int numResults = XMLFunctions.numResults(doc);
if ((numResults <= 0)) {
Log.i("doInBack", "nussun risultato");
DettagliPagina.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Nessun risultato trovato", Toast.LENGTH_LONG).show();
}
});
Intent intent = new Intent(DettagliPagina.this, FiltriAnagraficaPagina.class);
startActivity(intent);
}
Bundle extras = getIntent().getExtras();
int id = 0;
System.out.print(id);
if (extras != null) {
id = extras.getInt("id");
}
Log.i("Dettagli", "D1");
Set<Anagrafica> anagrafici = new HashSet<Anagrafica>();
NodeList nodes = doc.getElementsByTagName("anagrafica");
Element e = (Element) nodes.item(id);
anagrafica = new Anagrafica();
anagrafica.setId(XMLFunctions.getValue(e, "idAnagrafica"));
anagrafica.setNome(XMLFunctions.getValue(e, "nome"));
anagrafica.setCognome(XMLFunctions.getValue(e, "cognome"));
anagrafica.setIndirizzo(XMLFunctions.getValue(e, "indirizzo"));
anagrafica.setDataDiNascita(XMLFunctions.getValue(e, "dataDiNascita"));
anagrafica.setEmail(XMLFunctions.getValue(e, "email"));
anagrafica.setTipologiaUtente(XMLFunctions.getValue(e, "tipologieUtente"));
anagrafica.setAziendaCollegata(XMLFunctions.getValue(e, "aziendaCollegata"));
anagrafica.setTelefono(XMLFunctions.getValue(e, "telefono"));
anagrafica.setCellulare(XMLFunctions.getValue(e, "cellulare"));
anagrafica.setInteressi(XMLFunctions.getValue(e, "interessi"));
anagrafica.setRiferimenti(XMLFunctions.getValue(e, "riferimenti"));
anagrafici.add(anagrafica);
HashMap<String, String> map = new HashMap<String, String>();
map.put("idAnagrafica",anagrafica.getId());
map.put("nomeCognome",anagrafica.getNome() + " " + anagrafica.getCognome());
map.put("indirizzo", "Indirizzo: " + anagrafica.getIndirizzo());
map.put("dataDiNascita", "Data Nascita: " + anagrafica.getDataDiNascita());
map.put("email", "Email: " + anagrafica.getEmail());
map.put("tipologieUtente", "Tipologie Utente: " + anagrafica.getTipologiaUtente());
map.put("aziendaCollegata", "Azienda Collegata: " + anagrafica.getAziendaCollegata());
map.put("telefono", "Telefono: " + anagrafica.getTelefono());
map.put("cellulare", "Cellulare: " + anagrafica.getCellulare());
map.put("interessi", "Interessi: " + anagrafica.getInteressi());
map.put("riferimenti", "Riferimenti" + anagrafica.getRiferimenti());
mylist.add(map);
Log.i("Dettagli", "D2");
return mylist;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(DettagliPagina.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
final ListAdapter adapter = new SimpleAdapter(DettagliPagina.this, mylist, R.layout.dettagli,
new String[] { "nomeCognome", "dataDiNascita",
"tipologieUtente", "aziendaCollegata", "email",
"telefono", "cellulare", "interessi", "indirizzo",
"riferimenti" },
new int[] { R.id.tvNomeCognome, R.id.tvDataDiNascita,
R.id.tvTipologiaUtente, R.id.tvAziendaCollegata,
R.id.tvEmail, R.id.tvTelefono, R.id.tvCellulare,
R.id.tvInteressi, R.id.tvIndirizzo, R.id.tvRiferimenti });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "ID '" + o.get("idAnagrafica") + "' was clicked.",
Toast.LENGTH_LONG).show();
}
});
progressDialog.dismiss();
}
}
public class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}
here's the detail xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvNomeCognome"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawableLeft="#drawable/icon"
android:drawablePadding="10dp"
android:padding="7dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="#+id/tvTipologiaUtente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDataDiNascita"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="email"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvTelefono"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="phone"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvCellulare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="phone"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvInteressi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvAziendaCollegata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvIndirizzo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvRiferimenti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<Button
android:id="#+id/bCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/chiama" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Seems like you forgot to call setContentView(R.layout.your_layout); in your onCreate method
That button might not be part of the ListView, just of the main layout of that Activity.
If I understand what you're saying, you have a main view containing a ListView and a Button. If that affirmation is right, then you need to use an Activity instead of ListActivity or use :
mActivity= this ;
Button button = new Button(this);
button.setText("push me");
button.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mActivity, "push", Toast.LENGTH_SHORT).show();
}
});
getListView().addFooterView(button);
Be sure to call addFooterView(View v) before setAdapter(ListAdapter adapter)
Instead of use OnClickListener, please try to use onItemClikListener.
You are in a ListActivity, so I think (maybe I'm wrong) that what you want is to make call with the selected row. So remove bCall and its onClickListener and try
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:3492395504"));
startActivity(callIntent);
}
});
You are getting an NPE because you are trying to do this:
bCall = (Button) findViewById(R.id.bCall);
When you haven't set a layout for the screen.
That button is in your list row layout so you need to set it's function in your list adapter.
If I'm understanding your code, you are kicking off an AsyncTask in onCreate, that sets the listAdaper within its onPostExecute method. Also, in onStart you are attempting to get the button bCall.
However, if onStart executes before your background task has completed, then you will not yet have set the adapter, thus your button will not exist and your call (Button) findViewById(R.id.bCall) will return null

Categories

Resources