Android Studio "Unfortunately my project has stopped" - java

The project itself does not report any error, but when I run my project with the emulator, it popped up "Unfortunately project has stopped", can anyone look at my project and know what error is? I got following logcat error:
Process: edu.drexel.weatherundergroundapi, PID: 1800
java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.drexel.weatherundergroundapi/edu.drexel.weatherundergroundapi.MainActivity}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
at edu.drexel.weatherundergroundapi.CustomListAdapter.<init>(CustomListAdapter.java:35)
at edu.drexel.weatherundergroundapi.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
There are three java classes and three xml files: 1. MainActivity.java 2. CustomListAdapter.java 3. MyBgTask.java 4. listView.xml
5. activity_main.xml
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyBgTask asyncTask = new MyBgTask();
CustomListAdapter adapter = new CustomListAdapter(this, asyncTask.getTimeArray(), asyncTask.getConditionArray(),
asyncTask.getTempArray(), asyncTask.getHumidityArray(), asyncTask.getUrls());
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
asyncTask.execute();
}
/*public void onListItemClick(ListView lv, View view, int position, int imgid) {
String Slecteditem= (String)getListAdapter().getItem(position);
Toast.makeText(this, Slecteditem, Toast.LENGTH_SHORT).show();
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
CustomListAdapter.java:
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] time;
private final String[] condition;
private final String[] temp;
private final String[] humidity;
private final String[] url;
public CustomListAdapter(Activity context, String[] time, String[] condition, String[] temp, String[] humidity, String[] url)
{
super(context, R.layout.listview, time);
this.context = context;
this.time = time;
this.condition = condition;
this.temp = temp;
this.humidity = humidity;
this.url = url;
}
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Error getting bitmap", e.toString());
}
return bm;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview, null, true);
TextView timeView = (TextView) rowView.findViewById(R.id.dateTime);
TextView conditionView = (TextView) rowView.findViewById(R.id.condition);
TextView tempView = (TextView) rowView.findViewById(R.id.temp);
TextView humidityView = (TextView) rowView.findViewById(R.id.humidity);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
timeView.setText(time[position]);
conditionView.setText(condition[position]);
tempView.setText(temp[position]);
humidityView.setText(humidity[position]);
imageView.setImageBitmap(getImageBitmap(url[position]));
return rowView;
}
}
MyBgTask.java
public class MyBgTask extends AsyncTask<Void, Void, Void> {
String[] timeArray;
String[] conditionArray;
String[] tempArray;
String[] humidityArray;
String[] urls;
public String[] getTimeArray() {
return timeArray;
}
public String[] getConditionArray() {
return conditionArray;
}
public String[] getTempArray() {
return tempArray;
}
public String[] getHumidityArray() {
return humidityArray;
}
public String[] getUrls() {
return urls;
}
#Override
protected Void doInBackground(Void... params) {
try {
// Get User Current Location
String geoURL = "http://api.wunderground.com/api/56419d324b9bf190/geolookup/q/autoip.json";
URL url = new URL(geoURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
request.getContent();
JsonParser geo_jp = new JsonParser();
JsonElement geo_root = geo_jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject geo_rootobj = geo_root.getAsJsonObject();
String city = geo_rootobj.get("location").getAsJsonObject().get("city").getAsString();
String state = geo_rootobj.get("location").getAsJsonObject().get("state").getAsString();
String zip = geo_rootobj.get("location").getAsJsonObject().get("zip").getAsString();
// Invoke hourly weather forcast with user's current location
String forecastURL = "http://api.wunderground.com/api/56419d324b9bf190/conditions/hourly/forecast/q/" + zip + ".json";
URL furl = new URL(forecastURL);
HttpURLConnection forecastRequest = (HttpURLConnection) furl.openConnection();
forecastRequest.connect();
forecastRequest.getContent();
JsonParser forecast_jp = new JsonParser();
JsonElement forecast_root = forecast_jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray forecast_array = forecast_root.getAsJsonObject().get("hourly_forcast").getAsJsonArray();
for (int hour = 0; hour < forecast_array.size(); hour++) {
String month = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("mon_abbrev").getAsString();
String monthDay = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("mday_padded").getAsString();
String time = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("civil").getAsString();
String dateAndtime = month + " " + monthDay + " " + time;
String condition = forecast_array.get(hour).getAsJsonObject().
get("condition").getAsString();
String temp = forecast_array.get(hour).getAsJsonObject().
get("temp").getAsJsonObject().
get("english").getAsString();
String humidity = forecast_array.get(hour).getAsJsonObject().
get("humidity").getAsString();
String icon_url = forecast_array.get(hour).getAsJsonObject().
get("icon_url").getAsString();
timeArray[hour] = dateAndtime;
conditionArray[hour] = condition;
tempArray[hour] = temp;
humidityArray[hour] = humidity;
urls[hour] = icon_url;
}
} catch (IOException e) {
Log.e("ERROR", e.toString());
}
return null;
}
protected void onPostExecute(Void... params) {
}
}
listView.xml
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#33CC33"
android:text="#string/dateTime" />
<TextView
android:id="#+id/condition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/condition"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/temp"
android:layout_marginLeft="10dp" />
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/humidity"
android:layout_marginLeft="10dp" />
</LinearLayout>
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:clickable="false"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" >
</ListView>

Based on what I can see, the program crashes because time is null at this line:
public CustomListAdapter(Activity context, String[] time, String[] condition, String[] temp, String[] humidity, String[] url){
super(context, R.layout.listview, time);
...
}
This is because, as #codeMagic said in the comments, you are using the AsyncTask class incorrectly. The following code in your onCreate method
MyBgTask asyncTask = new MyBgTask();
CustomListAdapter adapter = new CustomListAdapter(this, asyncTask.getTimeArray(), asyncTask.getConditionArray(),
asyncTask.getTempArray(), asyncTask.getHumidityArray(), asyncTask.getUrls());
Creates an AsyncTask, but doesn't execute() it. When you call getTimeArray(), it returns the value of timeArray, which is a default-initialised null value.
Broadly, you need to
Execute the AsyncTask
Update the ArrayListAdapter when the task is done

Related

onClick error on passing the data from jsonarray to table view

I'm trying to pass the data from my json array to tableview (its the only one that I found that has an example similar to mine compared to listview) and my app always crashes when I always click my show button and I'm lost because of it.
heres my code :
my code for getting the data from jsonarray:
public class bTSQLClient extends AppCompatActivity {
////for populating the table
private final Context context;
private SimpleTableDataAdapter adapter;
TableView<String[]> tableView;
TableHelper tableHelper;
//getting the current sysID use in protected params
private static final String KEY_SYS_ID = "sys_id";
private int sys_Id = SharedPrefManager.getInstance(this).getUserid();
//View Branch
private static final String KEY_VB_ID = "branchid";
private static final String KEY_VB_USER = "username";
private static final String KEY_VB_PASSWORD = "password";
private static final String KEY_VB_NAME = "branchname";
private static final String KEY_VB_SYSID = "sys_id";
private static final String KEY_VB_CREATED = "created";
private static final String KEY_VB_UT = "user_type";
private int viewBranchID;
private String viewBranchUser;
private String viewBranchPassword;
private String viewBranchName;
private int viewBranchSYSID;
private int viewBranchCreated;
private String viewBranchUT;
//for populating the table
public bTSQLClient(Context context) {
this.context = context;
}
/**
* get Branch Data Operation table populate
*/
public void retrieve(final TableView tableView){
final ArrayList<branchlist> branchList = new ArrayList<>();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
Constants.viewbranches_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject;
branchlist b;
try
{
for (int i = 0; i < response.length(); i++)
{
jsonObject = response.getJSONObject(i);
//viewBranchID = jsonObject.getInt(KEY_VB_ID);
viewBranchUser = jsonObject.getString(KEY_VB_USER);
//viewBranchPassword = jsonObject.getString(KEY_VB_PASSWORD);
viewBranchName = jsonObject.getString(KEY_VB_NAME);
//viewBranchSYSID = jsonObject.getInt(KEY_VB_SYSID);
//viewBranchCreated = jsonObject.getInt(KEY_VB_CREATED);
//viewBranchUT = jsonObject.getString(KEY_VB_UT);
b = new branchlist();
//b.setBranchid(viewBranchID);
b.setUsername(viewBranchUser);
//b.setPassword(viewBranchPassword);
b.setBranchname(viewBranchName);
//b.setSys_id(viewBranchSYSID);
//b.setCreated(viewBranchCreated);
//b.setUser_type(viewBranchUT);
branchList.add(b);
}
//set to table view
adapter = new SimpleTableDataAdapter(context,new TableHelper(context).returnBranchViewArray(branchList));
tableView.setDataAdapter(adapter);
} catch (JSONException e)
{
//e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
Log.e ( "response", "" + response );
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
Log.e ( "response", "" + error );
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_SYS_ID, String.valueOf(sys_Id));
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(jsonArrayRequest);
}
}
Heres the TableHelper Class
public class TableHelper {
Context context;
private String[] branchViewHeader = {"Branch Name", "Username"};
private String[][] branchView;
public TableHelper(Context context){
this.context = context;
}
public String[] getBranchViewHeader()
{
return branchViewHeader;
}
public String[][] returnBranchViewArray(ArrayList<branchlist> branchList)
{
branchView = new String[branchList.size()][2];
branchlist b;
for(int i = 0; i<branchList.size();i++){
b = branchList.get(i);
branchView[i][0]=b.getBranchname();
branchView[i][1]=b.getUsername();
}
return branchView;
}
}
branchlist class
public class branchlist {
private int branchid;
private String username;
private String password;
private String branchname;
private int sys_id;
private int created;
private String user_type;
public int getBranchid(){
return branchid;
}
public void setBranchid(int branchid){
this.branchid = branchid;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public String getBranchname(){
return branchname;
}
public void setBranchname(String branchname){
this.branchname = branchname;
}
public int getSys_id(){
return sys_id;
}
public void setSys_id(int sys_id){
this.sys_id = sys_id;
}
public int getCreated(){
return created;
}
public void setCreated(int created){
this.created = created;
}
public String getUser_type(){
return user_type;
}
public void setUser_type(String user_type){
this.user_type = user_type;
}
public String toString(){
return branchname;
}
}
heresmy code for branch(the code that the bTSQLClient will pass to)
public class branch extends AppCompatActivity {
////for populating the table
private SimpleTableDataAdapter adapter;
TableView<String[]> tableView;
TableHelper tableHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_branch);
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, login.class));
return;
}
//for populating table
tableHelper = new TableHelper(this);
tableView = (TableView<String[]>) findViewById(R.id.tableView);
tableView.setColumnCount(2);
tableView.setHeaderBackgroundColor(Color.parseColor("#2ecc71"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,tableHelper.getBranchViewHeader()));
}
/**
* Show populated Table
*/
public void onTableshow(View view){ // The Error is right here (bTSQLClient is the above code)
new bTSQLClient(branch.this).retrieve(tableView);
}
/**
* goto Popup on Add Branch Account
*/
public void onAddBranch(View view){
startActivity(new Intent(branch.this,popup_addbranch.class));
}
/**
* Menu Signout
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menuLogout:
SharedPrefManager.getInstance(this).isLoggedOut();
finish();
startActivity(new Intent(this, login.class));
break;
}
return true;
}
/**
* Back to dashboard
*/
public void onBack(View view) {
startActivity(new Intent(branch.this, dashboard.class));
}
}
and Heres my postman response for my php code:
[
{
"branchid": 12,
"username": "king",
"password": "202cb962ac59075b964b07152d234b70",
"branchname": "123branch",
"sys_id": 8,
"created": "2019-10-28 20:45:08",
"user_type": "Branch"
},
{
"branchid": 13,
"username": "makoy",
"password": "bda639c314e39023789c37d7a07469f9",
"branchname": "makoy",
"sys_id": 8,
"created": "2019-10-28 20:50:41",
"user_type": "Branch"
},
{
"branchid": 14,
"username": "foodbranch",
"password": "202cb962ac59075b964b07152d234b70",
"branchname": "foodbranch",
"sys_id": 8,
"created": "2019-10-28 22:01:59",
"user_type": "Branch"
},
{
"branchid": 15,
"username": "081nao397",
"password": "7815696ecbf1c96e6894b779456d330e",
"branchname": "testingbranchname",
"sys_id": 8,
"created": "2019-11-08 08:21:01",
"user_type": "Branch"
},
{
"branchid": 16,
"username": "testing101",
"password": "7815696ecbf1c96e6894b779456d330e",
"branchname": "rest",
"sys_id": 8,
"created": "2019-11-08 08:28:55",
"user_type": "Branch"
}
]
I think I am finally close to making this problem done since I managed to make the database part show a correct array (the result is the postman result that I posted above)
XML Codes
<?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"
android:orientation="vertical"
tools:context=".main.Functions.dash_branch.branch">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="30sp"
android:layout_marginTop="30sp"
android:onClick="onBack"
android:padding="10sp"
android:text="Back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.008"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"></Button>
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="30sp"
android:layout_marginRight="30sp"
android:onClick="onAddBranch"
android:padding="10sp"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.008"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"></Button>
</RelativeLayout>
<RelativeLayout
android:id="#+id/layoutviewbranch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.codecrafters.tableview.TableView
android:id="#+id/tableView"
android:layout_width="wrap_content"
android:layout_height="450sp"
app:tableView_columnCount="2">
</de.codecrafters.tableview.TableView>
</RelativeLayout>
<Button
android:layout_marginTop="20sp"
android:layout_gravity="center"
android:onClick="onTableshow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show">
</Button>
</LinearLayout>
Logcat Error
FATAL EXCEPTION: main
Process: com.example.sample1myapp, PID: 25355
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7125) 
at android.view.View.performClickInternal(View.java:7102) 
at android.view.View.access$3500(View.java:801) 
at android.view.View$PerformClick.run(View.java:27336) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null object
reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:118)
at com.example.sample1myapp.System.RequestHandler.getRequestQueue(RequestHandler.java:30)
at com.example.sample1myapp.System.RequestHandler.<init>(RequestHandler.java:16)
at com.example.sample1myapp.System.RequestHandler.getInstance(RequestHandler.java:21)
at com.example.sample1myapp.main.Functions.dash_branch.bTSQLClient.retrieve(bTSQLClient.java:146)
at com.example.sample1myapp.main.Functions.dash_branch.branch.onTableshow(branch.java:78)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:7125) 
at android.view.View.performClickInternal(View.java:7102) 
at android.view.View.access$3500(View.java:801) 
at android.view.View$PerformClick.run(View.java:27336) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to implement DropDownMenu https://github.com/JayFang1993/DropDownMenu
I've got a problem with this code :
MainActivity
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import com.jayfang.dropdownmenu.DropDownMenu;
import com.jayfang.dropdownmenu.OnMenuSelectedListener;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import com.sai.eventee.rss.ServiceStarter;
import com.sai.eventee.util.ScrimInsetsFrameLayout;
import com.sai.eventee.web.WebviewFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
NavDrawerCallback {
private Toolbar mToolbar;
private NavDrawerFragment mNavigationDrawerFragment;
public static String DATA = "transaction_data";
public static String EMBEDD_DATA = "embedd";
SharedPreferences prefs;
boolean openedByBackPress = false;
//=======================================================
private DropDownMenu mMenu;
private ListView mList;
private int city_index;
private int sex_index;
private int age_index;
private List<String> data;
final String[] arr1=new String[]{"全部城市","北京","上海","广州","深圳"};
final String[] arr2=new String[]{"性别","男","女"};
final String[] arr3=new String[]{"全部年龄","10","20","30","40","50","60","70"};
final String[] strings=new String[]{"选择城市","选择性别","选择年龄"};
private FloatingActionButton mFAB;
private FloatingActionMenu mFABMenu;
//=======================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupFAB();
boolean newDrawer = getResources().getBoolean(R.bool.newdrawer);
if (newDrawer == true) {
setContentView(R.layout.activity_main_alternate);
} else {
setContentView(R.layout.activity_main);
Helper.setStatusBarColor(MainActivity.this, getResources()
.getColor(R.color.myPrimaryDarkColor));
}
mMenu=(DropDownMenu)findViewById(R.id.menu);
mMenu.setmMenuCount(3);
mMenu.setmShowCount(6);
mMenu.setShowCheck(true);
mMenu.setmMenuTitleTextSize(16);
mMenu.setmMenuTitleTextColor(Color.parseColor("#777777"));
mMenu.setmMenuListTextSize(16);
mMenu.setmMenuListTextColor(Color.BLACK);
mMenu.setmMenuBackColor(Color.parseColor("#eeeeee"));
mMenu.setmMenuPressedBackColor(Color.WHITE);
mMenu.setmMenuPressedTitleTextColor(Color.BLACK);
mMenu.setmCheckIcon(R.drawable.ico_make);
mMenu.setmUpArrow(R.drawable.arrow_up);
mMenu.setmDownArrow(R.drawable.arrow_down);
mMenu.setDefaultMenuTitle(strings);
mMenu.setShowDivider(false);
mMenu.setmMenuListBackColor(getResources().getColor(R.color.white));
mMenu.setmMenuListSelectorRes(R.color.white);
mMenu.setmArrowMarginTitle(20);
mMenu.setMenuSelectedListener(new OnMenuSelectedListener() {
#Override
public void onSelected(View listview, int RowIndex, int ColumnIndex) {
Log.i("MainActivity", "select " + ColumnIndex + " column and " + RowIndex + " row");
if (ColumnIndex == 0) {
city_index = RowIndex;
} else if (ColumnIndex == 1) {
sex_index = RowIndex;
} else {
age_index = RowIndex;
}
//过滤筛选
setFilter();
}
});
List<String[]> items = new ArrayList<>();
items.add(arr1);
items.add(arr2);
items.add(arr3);
mMenu.setmMenuItems(items);
mMenu.setIsDebug(false);
mList=(ListView)findViewById(R.id.lv_list);
data=getData();
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, data));
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mNavigationDrawerFragment = (NavDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_drawer);
if (newDrawer == true) {
mNavigationDrawerFragment.setup(R.id.scrimInsetsFrameLayout,
(DrawerLayout) findViewById(R.id.drawer), mToolbar);
mNavigationDrawerFragment
.getDrawerLayout()
.setStatusBarBackgroundColor(
getResources().getColor(R.color.myPrimaryDarkColor));
((ScrimInsetsFrameLayout) findViewById(R.id.scrimInsetsFrameLayout)).getLayoutParams().width = getDrawerWidth();
} else {
mNavigationDrawerFragment.setup(R.id.fragment_drawer,
(DrawerLayout) findViewById(R.id.drawer), mToolbar);
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationDrawerFragment.getView().getLayoutParams();
params.width = getDrawerWidth();
mNavigationDrawerFragment.getView().setLayoutParams(params);
}
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
// setting push enabled
String push = getString(R.string.rss_push_url);
if (null != push && !push.equals("")) {
// Create object of SharedPreferences.
boolean firstStart = prefs.getBoolean("firstStart", true);
if (firstStart) {
final ServiceStarter alarm = new ServiceStarter();
SharedPreferences.Editor editor = prefs.edit();
alarm.setAlarm(this);
// now, just to be sure, where going to set a value to check if
// notifications is really enabled
editor.putBoolean("firstStart", false);
// commits your edits
editor.commit();
}
}
// Checking if the user would prefer to show the menu on start
boolean checkBox = prefs.getBoolean("menuOpenOnStart", false);
if (checkBox == true) {
mNavigationDrawerFragment.openDrawer();
}
// New imageloader
Helper.initializeImageLoader(this);
}
private void setFilter(){
List<String> temp=new ArrayList<String>();
for (int i=0;i<getData().size();i++){
boolean city=((city_index==0)?true:data.get(i).contains(arr1[city_index]));
boolean sex=((sex_index==0)?true:data.get(i).contains(arr2[sex_index]));
boolean age=((age_index==0)?true:data.get(i).contains(arr3[age_index]));
if(city && sex && age){
temp.add(data.get(i));
}
}
mList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,temp));
}
private List<String> getData(){
List<String> data = new ArrayList<String>();
data.add("上海-男-10");
data.add("上海-男-20");
data.add("上海-男-30");
data.add("上海-男-40");
data.add("上海-男-50");
data.add("上海-男-60");
data.add("上海-男-70");
data.add("广州-男-10");
data.add("广州-女-10");
data.add("北京-男-20");
data.add("北京-女-10");
data.add("广州-男-10");
data.add("北京-男-10");
data.add("广州-男-10");
data.add("上海-女-60");
data.add("上海-女-20");
return data;
}
private void setupFAB() {
//define the icon for the main floating action button
ImageView iconFAB = new ImageView(this);
iconFAB.setImageResource(R.drawable.ic_action_new);
//set the appropriate background for the main floating action button along with its icon
mFAB = new FloatingActionButton.Builder(this)
.setContentView(iconFAB)
.setBackgroundDrawable(R.drawable.selector_button_red)
.build();
//define the icons for the sub action buttons
ImageView iconSortName = new ImageView(this);
iconSortName.setImageResource(R.drawable.ic_action_alphabets);
ImageView iconSortDate = new ImageView(this);
iconSortDate.setImageResource(R.drawable.ic_action_calendar);
ImageView iconSortRatings = new ImageView(this);
iconSortRatings.setImageResource(R.drawable.ic_action_important);
//set the background for all the sub buttons
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_button_gray));
//build the sub buttons
SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
SubActionButton buttonSortDate = itemBuilder.setContentView(iconSortDate).build();
SubActionButton buttonSortRatings = itemBuilder.setContentView(iconSortRatings).build();
/*
//to determine which button was clicked, set Tags on each button
buttonSortName.setTag(TAG_SORT_NAME);
buttonSortDate.setTag(TAG_SORT_DATE);
buttonSortRatings.setTag(TAG_SORT_RATINGS);
buttonSortName.setOnClickListener(this);
buttonSortDate.setOnClickListener(this);
buttonSortRatings.setOnClickListener(this);
*/
//add the sub buttons to the main floating action button
mFABMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonSortName)
.addSubActionView(buttonSortDate)
.addSubActionView(buttonSortRatings)
.attachTo(mFAB)
.build();
}
//===============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.rss_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onNavigationDrawerItemSelected(int position, NavItem item) {
Fragment fragment;
try {
fragment = item.getFragment().newInstance();
if (fragment != null) {
Bundle bundle = new Bundle();
String extra;
String license = getResources().getString(R.string.google_play_license);
// if item does not require purchase, or app has purchased, or license is null/empty (app has no in app purchases)
if (item.requiresPurchase() == true
&& !SettingsFragment.getIsPurchased(this)
&& null != license && !license.equals("")) {
fragment = new SettingsFragment();
extra = SettingsFragment.SHOW_DIALOG;
} else {
extra = item.getData();
}
bundle.putString(DATA, extra);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
setTitle(item.getText());
if (null != MainActivity.this.getSupportActionBar()
&& null != MainActivity.this.getSupportActionBar()
.getCustomView()) {
MainActivity.this.getSupportActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE);
}
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentById(
R.id.container);
if (mNavigationDrawerFragment.isDrawerOpen()) {
mNavigationDrawerFragment.closeDrawer();
} else if (webview instanceof WebviewFragment) {
boolean goback = ((WebviewFragment) webview).canGoBack();
if (!goback)
super.onBackPressed();
} else {
super.onBackPressed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment frag : fragments)
frag.onActivityResult(requestCode, resultCode, data);
}
}
private int getDrawerWidth(){
// Navigation Drawer layout width
int width = getResources().getDisplayMetrics().widthPixels;
TypedValue tv = new TypedValue();
int actionBarHeight;
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
} else {
actionBarHeight = 0;
}
int possibleMinDrawerWidth = width - actionBarHeight;
int maxDrawerWidth = getResources().getDimensionPixelSize(R.dimen.drawer_width);
return Math.min(possibleMinDrawerWidth, maxDrawerWidth);
}
}
Activity_main.xml
<?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">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.jayfang.dropdownmenu.DropDownMenu
android:orientation="horizontal"
android:layout_width="fill_parent"
android:id="#+id/menu"
android:background="#color/ripple_material_dark"
android:layout_height="60dp"/>
<ListView
android:layout_width="fill_parent"
android:layout_below="#id/menu"
android:id="#+id/lv_list"
android:background="#ffffff"
android:layout_height="wrap_content"></ListView>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.sai.eventee.NavDrawerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/drawer_fragment"
tools:layout="#layout/drawer_fragment" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
And Logcat:
10-04 22:48:47.884 27075-27075/com.sai.eventee E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sai.eventee, PID: 27075
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sai.eventee/com.sai.eventee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.access$800(ActivityThread.java:176)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5576)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
at com.sai.eventee.MainActivity.onCreate(MainActivity.java:90)
at android.app.Activity.performCreate(Activity.java:6005)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
            at android.app.ActivityThread.access$800(ActivityThread.java:176)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
            at android.os.Handler.dispatchMessage(Handler.java:111)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5576)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
I have no idea why I get a null pointer exception.
It means that findViewById(R.id.activity_main_alternate) returns null for mMenu. Does your activity_main_alternate.xml have the R.id.menu view?

Android Custom BaseAdapter getView not called

So, I have scoured the interwebs and I cannot find a solution for this based on other people's experiences, so I am posting this issue. (Please note that this is my 1st android app experience and I am debugging / updating an existing app.)
When I implement my custom NotesListAdapter (extends BaseAdapter) on the ListView, mListNotesView (mListNotesView.setAdapter(this)), and load the data into the ArrayList mNoteList, the getView function is not being called. Also, I found that mListNotesView.setBackgroundResource is not chaning the background of the control, either. I have a similar implementation on a previous activity that works exactly correct. When I copied over the class and changed it to handle my ArrayList, it broke. I have getCount returning the ArrayList size(), which is not 0, and getItemId returns position. I have a feeling it may be my XML or my setup because it's acting like the ListView is not visible. I am perplexed. How do I get the ListView to show? Anything inside of the getView has not been reached so it may be buggy.
ViewTicketOrderActivity (Some parts ommitted for size)
public class ViewTicketOrderActivity extends Activity {
MySQLDatabase myDataBase;
Ticket mTicket;
public ArrayList<Notes> mNotes = new ArrayList<Notes>();
String mErrorString;
Button mAddUpdateButton;
Button mAcceptButton;
//Button mViewNotesButton;
NotesListAdapter mNotesListAdapter;
static final int ERROR_DIALOG = 0;
static final int SUCCESS_DIALOG = 1;
static final int COMPLETED_DIALOG = 2;
static final int RESTART_DIALOG = 3;
static final int LOADING = 0;
static final int LOAD_ERROR = 1;
static final int LOADED = 4;
static final String TICKET_EXTRA = "ticket_extra";
static final String TAG = "ViewTicketOrderActivity";
private static final boolean gDebugLog = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewticketorder);
Activity context = this;
String theTitle = "Sundance Ticket Order";
theTitle += (MySQLDatabase.TESTING == true) ? " (DEV SERVER)" : " (LIVE)";
setTitle(theTitle);
myDataBase = MySQLDatabase.getMySQLDatabase(this);
if (gDebugLog) {
DebugLogger.logString(TAG, ".onCreate");
}
mNotesListAdapter = new NotesListAdapter(context, R.id.note_list);
Log.d(this.toString(),this.mNotesListAdapter.toString());
}
private class NotesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Notes> mNoteList;
private ListView mListNotesView;
private Activity mActivity;
int mState = LOADING;
String mErrorMessage;
private NotesListAdapter(Activity context, int listViewID) {
mActivity = context;
mNoteList = new ArrayList<Notes>();
mInflater = LayoutInflater.from(context);
mListNotesView = (ListView)context.findViewById(listViewID);
mListNotesView.setBackgroundResource(R.color.emergency_red);
mListNotesView.setAdapter(this);
Log.d(mListNotesView.toString(), String.valueOf(mListNotesView.getCount()));
this.notifyDataSetChanged();
//mListNotesView.setVisibility(View.VISIBLE);
}
void setLoading()
{
mState = LOADING;
this.notifyDataSetChanged();
}
void setLoadError(String errorString)
{
mState = LOAD_ERROR;
mErrorMessage = errorString;
this.notifyDataSetChanged();
}
void setNoteList(ArrayList<Notes> inNotes)
{
mState = LOADED;
mNoteList.clear();
mNoteList.addAll(inNotes);
Log.d("SetNoteList", "TRUE " + inNotes);
//mNoteList = mNotes;
this.notifyDataSetChanged();
}
/**
* Use the array index as a unique id.
*
* #see android.widget.ListAdapter#getItemId(int)
*/
#Override
public long getItemId(int position) {
return position;
}
public int getCount(){
if (mState == LOADED) {
Log.d("getCount",String.valueOf(mNoteList.size()));
return mNoteList.size();
} else {
return 0;
}
}
/**
* Make a view to hold each row.
*
* #see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
Log.d("getView",this.toString());
if (mState == LOADED) {
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there
// is no need
// to reinflate it. We only inflate a new View when the
// convertView supplied
// by ListView is null.
Notes note = this.getItem(position);
if (convertView == null) {
/*if (ticket.emergency())
{
convertView = mInflater.inflate(R.layout.emergency_ticket_list_item_opt,
null);
}
else
{
convertView = mInflater.inflate(R.layout.ticket_list_item,
null);
}*/
convertView = mInflater.inflate(R.layout.noteslist_item,
null);
// Creates a ViewHolder and store references to the two
// children views
// we want to bind data to.
holder = new ViewHolder();
holder.noteText = (TextView) convertView
.findViewById(R.id.text_note);
holder.dateText = (TextView) convertView
.findViewById(R.id.text_note_date);
holder.createByText = (TextView) convertView
.findViewById(R.id.text_note_by);
holder.createByIDText = (TextView) convertView
.findViewById(R.id.text_note_by_id);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the
// TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.noteText.setText(note.note());
holder.dateText.setText(note.date());
holder.createByText.setText(note.createBy());
holder.createByIDText.setText(note.employeeID());
if(!mTicket.employeeID().equals(note.employeeID())){
convertView.setBackgroundResource(R.drawable.solid_purple);
}
} else if (mState == LOADING ) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.loading_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Loading tickets");
} else if (mState == LOAD_ERROR) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.load_error_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Error loading tickets");
String errorString = mErrorMessage != null ? mErrorMessage : "";
TextView errorText = (TextView)convertView.findViewById(R.id.errorText);
errorText.setText(errorString);
}
return convertView;
}
class ViewHolder {
TextView noteText;
TextView dateText;
TextView createByText;
TextView createByIDText;
}
//#Override
/*public int getCount() {
*//*if (mState == LOADED) {
*//*
Log.d("getCount mState " + mState,String.valueOf(mNoteList.size())+", "+String.valueOf(mNotes.size()));
return mNoteList.size();
*//*} else {
Log.d("getCount mState " + mState,"0");
return 0;
}*//*
}*/
#Override
public Notes getItem(int position) {
Log.d("getItem",mNoteList.get(position).toString());
return mNoteList.get(position);
}
#Override
public int getItemViewType (int position) {
int result = mState;
Log.d("getItemId",String.valueOf(position));
return result;
}
#Override
public int getViewTypeCount ()
{
return 4;
}
}
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
mTicket = (Ticket)extras.getSerializable(TICKET_EXTRA);
}
else
{
mTicket = new Ticket();
}
if (mTicket.emergency())
{
setContentView(R.layout.view_emergency_ticketorder);
}
else
{
setContentView(R.layout.viewticketorder);
}
if (gDebugLog)
{
DebugLogger.logString(TAG, ".onResume mTicket " + mTicket);
}
TicketCheckService.clearNotificationForNewTicket(mTicket);
new GetTicketTask().execute();
new GetNotesTask().execute();
updateDisplayedTicket();
}
private void updateDisplayedTicket() {
mAddUpdateButton = (Button)findViewById(R.id.addUpdateButton);
mAcceptButton = (Button)findViewById(R.id.acceptButton);
//mViewNotesButton = (Button)findViewById(R.id.viewNotesButton);
String ticketStatus = myDataBase.getDescriptionStringForStatusString(mTicket.status());
if(ticketStatus == "Job Rejected") {
mAddUpdateButton.setText("Restart Job");
} else {
mAddUpdateButton.setText("Add Update");
}
if(ticketStatus == "Requested") {
mAcceptButton.setText("Accept");
} else if(ticketStatus != "Requested") {
mAcceptButton.setText("Back");
}
//mViewNotesButton.setText(R.string.viewNotes);
TextView idText = (TextView)findViewById(R.id.textTicketID);
idText.setText(mTicket.id());
//TextView descriptionText = (TextView)findViewById(R.id.textDescription);
//descriptionText.setText(mTicket.description());
TextView titleText = (TextView)findViewById(R.id.textTitle);
titleText.setText(mTicket.title());
TextView storeIDText = (TextView)findViewById(R.id.textStoreID);
storeIDText.setText(mTicket.store());
String formatPhone;
TextView storePhoneText = (TextView)findViewById(R.id.textStorePhone);
if(mTicket.phoneNo().isEmpty()){
formatPhone = "NO PHONE NO.";
} else {
storePhoneText = (TextView) findViewById(R.id.textStorePhone);
formatPhone = mTicket.phoneNo().replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
storePhoneText.setOnClickListener(new CallClickListener(mTicket.phoneNo()));
}
storePhoneText.setText(formatPhone);
TextView categoryText = (TextView)findViewById(R.id.textCategory);
String categoryDescription = MySQLDatabase.getDescriptionStringForCategoryString(mTicket.category());
categoryText.setText(categoryDescription);
if(ticketStatus == "Completed Pending") {
showDialog(COMPLETED_DIALOG);
}
}
public void onClickAccept(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAcceptButton.getText() =="Accept") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new AcceptTicketTask().execute();
} else {
finish();
}
}
public void onClickAddUpdate(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAddUpdateButton.getText() =="Add Update") {
Intent i = new Intent(this, UpdateTicketActivity.class);
i.putExtra(UpdateTicketActivity.TICKET_EXTRA, mTicket);
startActivity(i);
} else if(mAddUpdateButton.getText() =="Restart Job") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new RestartTicketTask().execute();
}
}
private class AcceptTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "1", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString) {
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(SUCCESS_DIALOG);
mAcceptButton.setText("Back");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class RestartTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "7", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString)
{
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(RESTART_DIALOG);
mAcceptButton.setText("Done");
mAddUpdateButton.setText("Add Update");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class GetTicketTask extends AsyncTask<Void, Integer, Ticket>
{
String mError = null;
protected Ticket doInBackground(Void... parent) {
Ticket result = null;
try {
result = myDataBase.getTicketWithID(mTicket.id(), mTicket.employeeID());
} catch (IOException e) {
// TODO Auto-generated catch block
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Ticket result)
{
if (null != result) {
mTicket = result;
} else {
setLoadError(mError);
}
}
}
private class GetNotesTask extends AsyncTask<Void, Integer, ArrayList<Notes>> {
String mError = null;
protected ArrayList<Notes> doInBackground(Void... parent) {
ArrayList<Notes> result = new ArrayList<Notes>();
try {
result = myDataBase.getTicketNotes(mTicket.id());
} catch (IOException e) {
// TODO Auto-generated catch block
myDataBase.debugLog("Error caught" + e);
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ArrayList<Notes> result) {
if (null != result) {
Log.d("Result", result.toString());
mNotes = result;
} else {
Log.d("SetNoteList","FALSE");
mNotesListAdapter.setLoadError(mError);
}
}
}
private void updateDisplayedNotes(){
ArrayList<Notes> newNotes = mNotes;
if(newNotes != null) {
mNotesListAdapter.setNoteList(newNotes);
}
}
/*private class updateDisplayedNotes extends AsyncTask<Void, Integer, ArrayList<Notes>> {
public ArrayList<Notes> newNotes = new ArrayList<Notes>();
public updateDisplayedNotes(){
super();
Log.d(this.toString(), "Updating");
}
protected ArrayList<Notes> doInBackground(Void... parent) {
Log.d(this.toString(), "Background Task");
for (Notes note : mNotes) {
Log.d(this.toString(),note.toString());
if(note != null) {
Log.d(this.toString(), "Note Added");
newNotes.add(note);
}
}
return newNotes;
}
protected void onPostExecute(ArrayList<Notes> newNotes)
{
if(newNotes != null) {
mNotes.clear();
mNotes.addAll(newNotes);
mNotesListAdapter.setNoteList(mNotes);
}
}
}*/
void setLoadError(String error) {
setContentView(R.layout.load_error_view);
TextView messageText = (TextView)findViewById(R.id.message);
messageText.setText("Error loading ticket");
String errorString = error != null ? error : "";
TextView errorText = (TextView)findViewById(R.id.errorText);
errorText.setText(errorString);
finish();
}
}
viewticketorder.xml (where note_list is)
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context=".ViewTicketOrderActivity"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="#string/loadingTicket"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white_color"
android:textSize="20dp"
android:textIsSelectable="true"
android:background="#drawable/title_transparent_bg"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:text="#string/ticketID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textTicketID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:text="#string/storeID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textStoreID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textStorePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:paddingTop="2dp"
android:text="#string/category"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white_color"
android:focusable="true"
android:textIsSelectable="true"/>
</LinearLayout>
<ListView
android:id="#+id/note_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:divider="#drawable/ticket_item_divider"
android:dividerHeight="1dp"
tools:ignore="NestedWeights"
android:choiceMode="singleChoice"
android:clickable="true"
android:background="#drawable/title_transparent_bg">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/acceptButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:onClick="onClickAccept" />
<Button
android:id="#+id/addUpdateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:onClick="onClickAddUpdate" />
</LinearLayout>
</LinearLayout>
notelist_item.xml (inflator)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text_note_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFFFF"
android:orientation="vertical"
>
<TextView
android:id="#+id/text_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/text_item_color"
android:textSize="#dimen/big_text_item_size" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight=".70"
>
<TextView
android:id="#+id/text_note_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
</LinearLayout>
</LinearLayout>
I'm going to recommend you reorganize your code. Here are some general tips:
1) Keep your views like ListView in the Activity class. Don't try to inflate the view in your adapter class. So in your activity's onCreate() after setContentView() you should have something like:
ListView listView = (ListView) findViewById(R.id.listView);
2) Next you need to get the data that will be shown in the listview and store it in a list. I didn't see in your code where the data comes from, but let's just say it comes from a database. You should create something like an ArrayList and store the data that you want to show in the ListView in the ArrayList
3) Next you need to create an adapter and pass the list of data into the adapter.
4) Once this has been done the ListView now has an adapter that will supply data to it. If you've done everything correctly then the system will eventually call getView() automatically and your code inside that should run and render the view.
Not an exact solution, but hopefully this explanation will help you figure it out.

sunshine app crashing on emulator

i m completely beginner in android developing and following the tutorial for sunshine app, while running the app it was supposed to display the detail on detailactivity but gives error. help me figure it out
mainactivity
package com.example.android.sunshine.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
forecastFragment
package com.example.android.sunshine.app;
import android.content.Intent;
import android.net.*;
import android.os.*;
import android.support.v4.app.*;
import android.text.format.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import org.json.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
/**
* Created by Nabahat on 7/8/2015.
*/
public class ForecastFragment extends Fragment {
List<String> mWeekForecast;
ArrayAdapter<String> mForecastAdapter = null;
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String forecast = mForecastAdapter.getItem(position);
Intent intent = new Intent(getActivity(), DetailActivity.class )
.putExtra(Intent.EXTRA_TEXT, forecast);
startActivity(intent);
}
});
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time) {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
* <p/>
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay + i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("API_KEY", "c84aeef73dfe54e9ec696154cfb89a5a");
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.setDoOutput(false);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
mForecastAdapter.clear();
for (String dayForecastStr : result) {
mForecastAdapter.add(dayForecastStr);
}
}
}
}
}
detail activity
package com.example.android.sunshine.app;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)){
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(forecastStr);
}
return rootView;
}
}
}
activitydetail.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.DetailActivity$DetailFragment"
tools:layout="#layout/fragment_detail" android:layout_width="match_parent"
android:layout_height="match_parent" />
activitymain.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragmentdetail.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:paddingLeft="64dp"
android:paddingRight="64dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.android.sunshine.app.DetailFragment">
<TextView
android:id="#+id/detail_text"
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
fragmentmain.xml
<FrameLayout
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:paddingLeft="64dp"
android:paddingRight="64dp"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.sunshine.app.MainActivityFragment$PlaceholderFragment"
android:id="#+id/container">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
logcat
android.support.v7.internal.widget.ActionBarOverlayLayout{bd47b46 V.E..... ... 0,0-0,0 #7f0c003e app:id/decor_content_parent}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ContentFrameLayout{252c0107 V.E..... ... 0,0-0,0 #1020002 android:id/content}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.RelativeLayout{39c34c6e V.E..... ... 0,0-0,0 #7f0c004f app:id/fragment}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.AppCompatTextView{e76c234 V.ED.... ... 0,0-0,0 #7f0c0050 app:id/detail_text}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContainer{3ff4b85d V.ED.... ... 0,0-0,0 #7f0c003f app:id/action_bar_container}
07-09 22:24:29.826 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.Toolbar{4d05d2 V.E..... ... 0,0-0,0 #7f0c0040 app:id/action_bar}
07-09 22:24:29.828 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.TextView{2afda6a3 V.ED.... ... 0,0-0,0}
07-09 22:24:29.828 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContextView{1bd7cda0 G.E..... ... 0,0-0,0 #7f0c0041 app:id/action_context_bar}
07-09 22:24:29.829 12200-12200/com.example.android.sunshine.app D/AndroidRuntime﹕ Shutting down VM
07-09 22:24:29.830 12200-12200/com.example.android.sunshine.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.sunshine.app, PID: 12200
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.DetailActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6006)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-09 22:24:32.288 12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 70.244ms
07-09 22:24:40.045 12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 5.676ms
Your DetailActivity has the lines:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
But your activity_detail.xml as you've posted doesn't have any id named container - in fact, it already has a Fragment directly in the layout. You should remove the lines from your DetailActivity's onCreate().
In activitydetail.xml change android:id="#+id/fragment" to android:"#+id/container"

Android - Import database get nullpointerexception on rawquery

I followed this tutorial to import database. Then I try to read the data using ArrayList to display them in listview. But I got nullpointer exception on my rawQuery saying it is invoking a null object reference.
DB.java
public class DB extends SQLiteOpenHelper {
//The Android's default system path of your application database.
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
private static String TABLE_LOCATION = "Frasa";
private final Context context;
private SQLiteDatabase db;
// constructor
public DB(Context context) {
super( context , DB_NAME , null , 1);
this.context = context;
}
// Creates a empty database on the system and rewrites it with your own database.
public void create() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
// By calling this method and empty database will be created into the default system path
// of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// Check if the database exist to avoid re-copy the data
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String path = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
// database don't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
// copy your assets db to the new system DB
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
//Open the database
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch(SQLException sqle) {
db = null;
return false;
}
}
#Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// PUBLIC METHODS TO ACCESS DB CONTENT
// -----------------------------------------------------------------------------------------------------------------
public ArrayList<Frasa> getFrasa(String situation) {
//ArrayList of Frasa class objects
ArrayList<Frasa> arrFrasa = null;
//String query = "SELECT * FROM Frasa WHERE Situation = " + situation;
String selectQuery = "SELECT " +
Frasa.KEY_ID + "," +
Frasa.KEY_PHRASE + "," +
Frasa.KEY_TRANSLATE + "," +
Frasa.KEY_PRONOUNCE +
" FROM " + TABLE_LOCATION + " WHERE situation = " +situation;
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
Cursor curFrasa = db.rawQuery(selectQuery, null);
if (curFrasa != null && curFrasa.moveToFirst()) {
arrFrasa = new ArrayList<Frasa>();
while (curFrasa.isAfterLast() == false) {
//Frasa is a class with list of fields
Frasa fra = new Frasa();
fra.setId(curFrasa.getInt(curFrasa.getColumnIndex(Frasa.KEY_ID)));
fra.setPhrase(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PHRASE)));
fra.setTranslate(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_TRANSLATE)));
fra.setPronounce(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PRONOUNCE)));
arrFrasa.add(fra);
curFrasa.moveToNext();
}
}
curFrasa.close();
db.close();
return arrFrasa;
}
}
Frasa.java (Database table and columns)
public class Frasa {
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_PHRASE = "phrase";
public static final String KEY_TRANSLATE = "translate";
public static final String KEY_PRONOUNCE = "pronounce";
// property help us to keep data
public int id;
public String situation;
public String phrase;
public String translate;
public String pronounce;
public Frasa() {
}
public Frasa(int id, String situation, String phrase, String translate, String pronounce) {
this.id = id;
this.situation = situation;
this.phrase = phrase;
this.translate = translate;
this.pronounce = pronounce;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
public String getTranslate() {
return translate;
}
public void setTranslate(String translate) {
this.translate = translate;
}
public String getPronounce() {
return pronounce;
}
public void setPronounce(String pronounce) {
this.pronounce = pronounce;
}
}
public class GreetingAdapter extends ArrayAdapter<Frasa> {
Context context;
int layoutResourceId;
ArrayList<Frasa> data = new ArrayList<Frasa>();
public GreetingAdapter(Context context, int layoutResourceId, ArrayList<Frasa> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textPhrase = (TextView) row.findViewById(R.id.textViewPhrase);
holder.textTranslate = (TextView) row.findViewById(R.id.textViewTranslate);
holder.btnSpeak = (Button) row.findViewById(R.id.buttonSpeak);
holder.btnRecord = (Button) row.findViewById(R.id.buttonRecord);
holder.btnPlay = (Button) row.findViewById(R.id.buttonPlay);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Frasa frasa = data.get(position);
holder.textPhrase.setText(frasa.getPhrase());
holder.textTranslate.setText(frasa.getTranslate());
holder.btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Speak button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Play Button Clicked", "**********");
Toast.makeText(context, "Playing recorded audio",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textPhrase;
TextView textTranslate;
Button btnSpeak;
Button btnRecord;
Button btnPlay;
}
}
activity_list_greetings.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Greetings"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/black" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listGreetings"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/txt_header" />
list_item_greet.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewPhrase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phrase"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_above="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSpeak"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Speak"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonRecord"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSpeak"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Record"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonRecord"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Play"
android:textColor="#0099CC" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Translate"
android:textSize="20sp"
android:textColor="#color/background_material_dark"
android:layout_below="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
ListGreetings.java
public class ListGreetings extends ActionBarActivity {
TextView txtPhrase, txtTranslate;
Button speakButton;
MediaPlayer pronounce;
ListView userList;
GreetingAdapter greetAdapter;
//ArrayList<Frasa> frasaArray = new ArrayList<Frasa>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_greetings);
DB db = new DB(this);
db.open();
//get Frasa data
ArrayList<Frasa> frasaArray = db.getFrasa("Greetings");
/**
* set item into adapter
*/
greetAdapter = new GreetingAdapter(ListGreetings.this, R.layout.list_item_greet, frasaArray);
userList = (ListView) findViewById(R.id.listGreetings);
userList.setItemsCanFocus(false);
userList.setAdapter(greetAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_greetings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Is it my way of calling getFrasa wrong? Or the database cannot be detected? I'm sure I already pushed the database file to both assets folder & inside the package. Sorry, if I'm not formatting the codes correctly. Thanks in advance for any help.
The problem is that you are trying to open the Database from a different location
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
...
...
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
db is returning NULL because your database is stored in /assets folder not in "data/data/hairulhazri.malayforyou/databases/"

Categories