java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException - java

Seems like there are many questions that are similar to mine but the answers posted there dosen't seem to work for me. My program is supposed to simply just open up a new page that allows webview.
But when i try to open this page, errors show without many hints on where the problem lies.
public class DetailedEventActivity extends Activity {
TextView name;
TextView desc;
TextView link;
String pid;
String myName;
String myDesc;
String myLink;
Button eLink;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single profile url
private static final String url_event_detials = "http://10.0.2.2:8888/week_6/get_all_event.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENT = "event";
private static final String TAG_PID = "eventID";
private static final String TAG_NAME = "eventName";
private static final String TAG_DESC = "eventDescription";
private static final String TAG_LINK = "link";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_event);
// getting profile details from intent
Intent i = getIntent();
// getting profile id (pid) from intent
pid = i.getStringExtra(TAG_PID);
myName = i.getStringExtra(TAG_NAME);
myDesc = i.getStringExtra(TAG_DESC);
myLink = i.getStringExtra(TAG_LINK);
name = (TextView) findViewById(R.id.inputName);
desc = (TextView) findViewById(R.id.inputDesc);
//link = (TextView) findViewById(R.id.inputLink);
name.setText(myName);
desc.setText(myDesc);
link.setText(myLink);
eLink = (Button) findViewById(R.id.eventLink);
eLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WebView webview = new WebView(DetailedEventActivity.this);
setContentView(webview);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.loadUrl(myLink);
}
});
// Getting complete profile details in background thread
}
And the codes leads up to this other class.
public class ViewEventActivity extends ListActivity {
String pid;
String name;
String desc;
String link;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> eventList;
// url to get all profile list
private static String url_all_event = "http://10.0.2.2:8888/week_6/get_all_event.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENT = "event";
private static final String TAG_PID = "eventID";
private static final String TAG_NAME = "eventName";
private static final String TAG_DESC = "eventDescription";
private static final String TAG_LINK = "link";
// profiles JSONArray
JSONArray event = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_event);
// Hashmap for ListView
eventList = new ArrayList<HashMap<String, String>>();
// Loading profiles in Background Thread
new LoadAllEvent().execute();
// Get listview
ListView lv = getListView();
// on seleting single event
// launching Edit event Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
// String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
//Roy
String myPid = eventList.get(position).get(TAG_PID);
String myName = eventList.get(position).get(TAG_NAME);
String myDesc = eventList.get(position).get(TAG_DESC);
String myLink = eventList.get(position).get(TAG_LINK);
// Starting new intent
Intent in = new Intent(getApplicationContext(),DetailedEventActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, myPid);
Log.d("Put Extra ", "id = "+ myPid);
in.putExtra(TAG_NAME, myName);
Log.d("Put Extra ", "name = "+ myName);
in.putExtra(TAG_DESC, myDesc);
Log.d("Put Extra ", "desc = "+ myDesc);
in.putExtra(TAG_LINK, myLink);
Log.d("Put Extra ", "link = "+ myLink);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit profile Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted profile
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all profile by making HTTP Request
* */
class LoadAllEvent extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewEventActivity.this);
pDialog.setMessage("Loading event. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All profiles from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_event, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Event ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// profiles found
// Getting Array of profiles
event = json.getJSONArray(TAG_EVENT);
// looping through All profiles
for (int i = 0; i < event.length(); i++) {
JSONObject c = event.getJSONObject(i);
Log.d("View Json ", "i = "+i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
Log.d("View Json ", "id = "+ id);
String name = c.getString(TAG_NAME);
Log.d("View Json ", "name = "+ name);
String desc = c.getString(TAG_DESC);
Log.d("View Json ", "desc = "+ desc);
String link = c.getString(TAG_LINK);
Log.d("View Json ", "link = "+ link);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESC, desc);
map.put(TAG_LINK, link);
// adding HashList to ArrayList
eventList.add(map);
}
} else {
// no profiles found
// Launch Add New profile Activity
Intent i = new Intent(getApplicationContext(),
MainScreenActivity.class);
//Main Page Aagin
pDialog = new ProgressDialog(ViewEventActivity.this);
pDialog.setMessage("Redirecting to main page");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all profiles
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewEventActivity.this, eventList,
R.layout.list_event, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
And the error i keep getting on the LogCat is:
11-17 11:21:55.819: E/AndroidRuntime(1391): FATAL EXCEPTION: main
11-17 11:21:55.819: E/AndroidRuntime(1391): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.DetailedEventActivity}: java.lang.NullPointerException
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.os.Looper.loop(Looper.java:137)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-17 11:21:55.819: E/AndroidRuntime(1391): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 11:21:55.819: E/AndroidRuntime(1391): at java.lang.reflect.Method.invoke(Method.java:525)
11-17 11:21:55.819: E/AndroidRuntime(1391): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-17 11:21:55.819: E/AndroidRuntime(1391): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-17 11:21:55.819: E/AndroidRuntime(1391): at dalvik.system.NativeStart.main(Native Method)
11-17 11:21:55.819: E/AndroidRuntime(1391): Caused by: java.lang.NullPointerException
11-17 11:21:55.819: E/AndroidRuntime(1391): at com.example.test.DetailedEventActivity.onCreate(DetailedEventActivity.java:77)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.Activity.performCreate(Activity.java:5133)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-17 11:21:55.819: E/AndroidRuntime(1391): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-17 11:21:55.819: E/AndroidRuntime(1391): ... 11 more
I am aware that this question might seem trivial but i just started learning java last month, so guidiance and help is much appreciated. Thanks!

You are accessing the link object without a proper initialization:
//link = (TextView) findViewById(R.id.inputLink);
link.setText(myLink);

your textview link causes null pointer exception,
link.setText(myLink); // <-- null here
so change
//link = (TextView) findViewById(R.id.inputLink);
to
link = (TextView) findViewById(R.id.inputLink);

Related

Storing a spinner item in a string value

I have created an app that is connected to a remote database. The items in the database are displayed through a spinner in my MainActivity class. I want to display the selected item in a separate class(Map.java) and XML page(map.xml), So I used this code in Map.java to try get the selected item and display it:
Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);
To display this value I created an EditText in my map.xml file:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:text="#string/text"
android:id="#+id/editText1"
android:layout_alignBottom="#+id/textView"
android:layout_toRightOf="#+id/textView"
android:layout_alignRight="#+id/imageView"
android:layout_alignEnd="#+id/imageView" />
The android:input_type="text" is a string value I created:
<string name="text"> %s </string>
But whenever I open the map page my app crashes. Could someone please tell me where I am going wrong?
Here all of my code for MainActivity and Map.java
MainActivity
package com.example.cillin.infoandroidhivespinnermysql;
import java.util.ArrayList;
..
public class MainActivity extends Activity implements OnItemSelectedListener {
private Button btnAddNewCategory;
private TextView txtCategory;
public Spinner spinnerFood;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://192.168.1.4/food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://192.168.1.4/food_api/get_categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
spinnerFood = (Spinner) findViewById(R.id.spinFood);
txtCategory = (TextView) findViewById(R.id.txtCategory);
categoriesList = new ArrayList<Category>();
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
// Add new category click event
btnAddNewCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtCategory.getText().toString().trim().length() > 0) {
// new category name
String newCategory = txtCategory.getText().toString();
// Call Async task to create new category
new AddNewCategory().execute(newCategory);
} else {
Toast.makeText(getApplicationContext(),
"Please enter category name", Toast.LENGTH_SHORT)
.show();
}
}
});
new GetCategories().execute();
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
txtCategory.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerFood.setAdapter(spinnerAdapter);
//spinnerValue = spinnerFood.getSelectedItem().toString();
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching food categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
/**
* Async task to create a new food category
* */
private class AddNewCategory extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating new category..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String newCategory = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", newCategory));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// fetching all categories
new GetCategories().execute();
}
});
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Map.java
package com.example.cillin.infoandroidhivespinnermysql;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class Map extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the menu XML file
//SetContentView links a Java file, to its XML file for the layout
setContentView(R.layout.map);
/*TextView.setText(spinnerValue);
TextView spinv = (TextView)findViewById(R.id.textView2);
spinv.setText(getspin());
spinv = getspin();*/
Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);
Button mainm = (Button)findViewById(R.id.mainmenu);
mainm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This button is linked to the map page
Intent i = new Intent(Map.this, MainMenu.class);
//Activating the intent
startActivity(i);
}
});
}
}
Any help would be much appreciated!!
Here are the errors in my logcat when is crashes:
E/DatabaseUtils﹕ Writing exception to parcel
java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:14643)
at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2469)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:688)
at android.content.ContentProvider$Transport.call(ContentProvider.java:325)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:275)
at android.os.Binder.execTransact(Binder.java:404)
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.cillin.infoandroidhivespinnermysql, PID: 14691
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cillin.infoandroidhivespinnermysql/com.example.cillin.infoandroidhivespinnermysql.Map}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.cillin.infoandroidhivespinnermysql.Map.onCreate(Map.java:34)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
I'm guessing that you're getting a NullPointerException in your Map.class
Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);
You get a reference to Spinner, then you try to get the selected item and then convert that item to a string. As far as I can tell you haven't actually added any items to the spinner. My guess is that you are trying to access an object in the spinner and since it doesn't exist it returns null. Then you try to call a method on the null object and get an NPE.
This is just a guess. A stacktrace is very helpful in trying to diagnose this.
Where I think you're going wrong is that you populate the spinner in MainActivity and then expect to be able to select an item from that spinner from a different activity. This isn't how it works. Map.class won't be able to reference anything in MainActivity.class. You could try passing the object from MainActivity.class to Map.class or use a different method of passing data, but trying to reference data in MainAcitivity.class from Map.class won't work.
Edit:
If you just want to pass a String from MainActivity.class to Map.class you can add the string as an 'extra' to the intent that you use to start Map.class.
In your MainActivity.class code. When the item from the spinner is selected, create an intent and set the string as an extra using the putExtra() method. You will need to supply a key that basically tags the extra so you can identify it in the receiving activity and the string you want to send.
Intent intent = new Intent(this, Map.class);
intent.putExtra("KEY_SPINNER_STRING", variableRepresentingString);
startActivity(intent);
In the Map.class activity, in the onCreate() method you will need to receive the intent, check for the extra, then unpack the extra. Then you will have the String.
onCreate(Bundle savedInstanceState) {
String spinnerString;
if (getIntent() != null && getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
if (bundle.getString("KEY_SPINNER_STRING") != null) {
spinnerString = bundle.getString("KEY_SPINNER_STRING");
}
}
}
If everything is done correctly the String will be passed from MainActivity.class and received by Map.class

Null error in Activity trying to access SQLite table

Newbie question time again;
So within FormActivity I post then receive a response from a SQL table on a remote server, the data is put into a local SQLite table row. Then, I have a Fragment with several EditText fields which I try to populate with the local table data. Now, I have a method within the Activity, DrawText(), to do this but when ran I am getting a crash. The logcat message I put in shows that when the DrawText() is called the value it is pulling from the SQLite table is null.
I've moved the method around trying to make sure it accesses the table after it has already been populated from the server response, but cannot get it working. Any help would be greatly appreciated. Code below (now Edited with help)
FormActivity.java
public class FormActivity extends FragmentActivity {
//create variables & Logcat tag
private static final String TAG = FormActivity.class.getSimpleName();
private EditText inputTitle;
private EditText inputName;
private EditText inputSurname;
private SessionManager sm;
private SQLiteHandler db;
private ProgressDialog pDialog;
private String e_check;
private String surname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
//set inputs for fields
inputTitle = (EditText) findViewById(R.id.titleText);
inputName = (EditText) findViewById(R.id.foreText);
inputSurname = (EditText) findViewById(R.id.surnameText);
//initialise pager for swipe screens
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
//email value passed in
Bundle extras = getIntent().getExtras();
if (extras != null) {
e_check = extras.getString("e_check");
}
// SQLite database handler - delete old and recreate db from remote server data
db = new SQLiteHandler(getApplicationContext());
String email = e_check;
checkUserDetails(email);
//<!-- TODO: load db fields to textfields -->
//<!-- TODO: greeting toast -->
}
/**
* function to verify & retrieve details in mysql db
* */
private void checkUserDetails(final String email) {
// Tag used to cancel the request
String tag_string_req = "req_retrieve";
pDialog.setMessage("Retrieving details ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_RETRIEVE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Retrieval Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user exists
// fill in textfields
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
surname = user.getString("surname");
String email = user.getString("email");
String created_at = user
.getString("created_at");
String tel_no = user.getString("tel_no");
String home_add = user.getString("home_add");
String postcode = user.getString("postcode");
String postal = user.getString("postal");
// Inserting row in table
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 300ms
DrawText();
}
}, 300);
/* Displaying the user details on the screen
FirstFragment fragA = (FirstFragment) getSupportFragmentManager().findFragmentByTag("fragA");
fragA.DrawText();*/
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Retrieval Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "retrieve");
params.put("email", email);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
public void DrawText() {
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
if (user.size() != 0) {
//String surname = user.get("surname");
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}else{
Log.e(TAG, "something you want to say");
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return FourthFragment.newInstance("FourthFragment, Instance 1");
//case 4: return FifthFragment.newInstance("ThirdFragment, Instance 3");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
// Number of screens we want to swipe between
public int getCount() {
return 4;
}
}
#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_form, 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);
}
}
Logcat (also updated)
05-16 09:31:35.560 21981-21981/com.disclosure_scots.disclosure_scots D/FormActivity﹕ Retrieval Response: {"tag":"retrieve","error":false,"uid":"55558b80341dc0.72266271","user":{"name":"John","surname":"Carter","email":"cart#email.com","created_at":"2015-05-15 08:00:32","tel_no":"1231234123","home_add":"22 Lone Road","postcode":"G44 4TT","postal":"false"}}
05-16 09:31:35.643 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ Database tables created
05-16 09:31:35.663 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ New user inserted into sqlite: 1
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ Fetching user from Sqlite: {tel_no=1231234123, postal=false, email=cart#email.com, surname=Carter, name=John, created_at=2015-05-15 08:00:32, uid=55558b80341dc0.72266271, home_add=22 Lone Road, postcode=G44 4TT}
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots E/FormActivity﹕ string surname: Carter
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots D/AndroidRuntime﹕ Shutting down VM
05-16 09:31:35.981 21981-21981/com.disclosure_scots.disclosure_scots E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.disclosure_scots.disclosure_scots, PID: 21981
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.disclosure_scots.disclosure_scots.FormActivity.DrawText(FormActivity.java:180)
at com.disclosure_scots.disclosure_scots.FormActivity$1$1.run(FormActivity.java:125)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
The problem is that you are trying to collect data before adding data. As you can see you are calling DrawText(); just after the response received (before adding data to database). So obviously the data'll be null. You should call the DrawText(); after adding the data to the db.
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
DrawText();
If the above code doesn't work, try calling DrawText() after a 500ms like this
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
DrawText();
}
}, 500);
If nothing worked from above. declare String variables such as name,surname etc.. ( which you parsed from the JSON ) outside the methods which will extend the accessibility of the variable from any method and update the DrawText(); like this
private String surname;
.....{
....
surname = jsonObject.getString("surname");
...
}
public void DrawText() {
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}
public void DrawText() {
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
if (user.size() != 0) {
String surname = user.get("surname");
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}else{
Log.e(TAG, "something you want to say");}
}

FATAL EXCEPTION: main java.lang.ArrayIndexOutOfBoundsException:

i have problem when im trying to show data in list view from my database
the error is "FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4"
. i dont understand what is it.
i hope somebody can help me
thanks
this is my code
public class FragmentMaintain extends Fragment {
ListView list;
TextView mid;
TextView pid;
TextView status;
TextView description;
TextView note;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://10.0.2.2/skripsi/json/testing.php";
//JSON Node Names
private static final String TAG_OS = "maintenance";
private static final String TAG_MID = "mid";
private static final String TAG_PID = "pid";
private static final String TAG_STATUS = "status";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_NOTE = "note";
JSONArray maintenance = null;
Button Addnotedata;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ZZZ", "ada di oncreateView maintain");
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_maintain, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mid = (TextView) getActivity().findViewById(R.id.mid);
pid = (TextView) getActivity().findViewById(R.id.pid);
status = (TextView) getActivity().findViewById(R.id.status);
description = (TextView) getActivity().findViewById(R.id.description);
note = (TextView) getActivity().findViewById(R.id.note);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
//String pid = getArguments().getString("pid");
//List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("pid", pid));
JSONParser jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequestWithoutParams(url);
//Log.d("TES", pid+", "+ json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
maintenance = json.getJSONArray(TAG_OS);
for(int i = 0; i < maintenance.length(); i++){
JSONObject c = maintenance.getJSONObject(i);
// Storing JSON item in a Variable
String mid = c.getString(TAG_MID);
String pid = c.getString(TAG_PID);
String status = c.getString(TAG_STATUS);
String description = c.getString(TAG_DESCRIPTION);
String note = c.getString(TAG_NOTE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_MID, mid);
map.put(TAG_PID, pid);
map.put(TAG_STATUS, status);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_NOTE, note);
oslist.add(map);
list=(ListView) getActivity().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_maintain,
new String[] { TAG_MID,TAG_PID, TAG_STATUS, TAG_NOTE}, new int[] {
R.id.mid,R.id.pid, R.id.status, R.id.description, R.id.note});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " + oslist.get(+position).get("pid"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and this my logcat
10-10 00:10:50.575 2004-2004/com.example.blackcustomzier.skripsi
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:160)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:2177)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillFromTop(ListView.java:736)
at android.widget.ListView.layoutChildren(ListView.java:1655)
at android.widget.AbsListView.onLayout(AbsListView.java:2012)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
If the length is 4, max index should be 3 as the index starts from 0.
Try this way,hope this will help you to solve your problem.
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,R.layout.list_maintain,new String[] {TAG_MID,TAG_PID,TAG_STATUS,TAG_DESCRIPTION,TAG_NOTE}, new int[] { R.id.mid,R.id.pid, R.id.status, R.id.description, R.id.note});
You are missing to pass TAG_DESCRIPTION in String Array at adapter initialization.
When you create SimpleAdapter the 4th and 5th arguments need to be same size.
So strings of 4th argument will be used as keys to fill view with value of the map which is 3rd argument of constructor.
And the way matching a view with a key is specifying them in 4th and 5th arguments which are containing keys and containing ids of views respectively, to have same index in each array.
See this

Simple Android Image Parsing

I'm attempting to parse image URLs and show the images in a ListView, but I continue to receive the ProtocalNotFound Exception/JSON Exception No value for null. I am pretty sure I'm close to translating the image URLs into bitmaps, but I'm off by something small. Any ideas for the right approach would be helpful. My class is below including the URL for the feed. Right now, I'm trying to convert the image URL in the loadImageFromWebOperations method. Please let me know if you need more information.
Android Class:
public class mainViewController extends ListFragment
{
mainViewController context = this;
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
//private static final String READ_COMMENTS_URL = "https://shipstudent.com/androidapp/comments.php";
private static final String READ_COMMENTS_URL = "https://shipstudent.com/complaint_desk/androidcentralwall.php";
// JSON IDS:
#SuppressWarnings("unused")
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
#SuppressWarnings("unused")
private static final String TAG_POST_ID = "IDPosts";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "body";
private static final String TAG_PROFILE_PICTURE = "profile_picture";
//private static final String TAG_POSTED = "posted";
// it's important to note that the message is both in the parent branch of
// our JSON tree that displays a "Post Available" or a "No Post Available"
// message,
// and there is also a message for each individual post, listed under the
// "posts"
// category, that displays what the user typed as their message.
// An array of all of our comments
private JSONArray allPosts = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
public mainViewController()
{
}
String[] mainFeed = {};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// // TODO Auto-generated method stub
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(
// inflater.getContext(), android.R.layout.simple_list_item_1,
// mainFeed);
//
// setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
// Intent i = new Intent(ReadComments.this, writePostViewController.class);
// startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
allPosts = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < allPosts.length(); i++) {
JSONObject c = allPosts.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
File sdCard = Environment.getExternalStorageDirectory();
String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(" ", "%20"),sdCard.getAbsolutePath() + "/dir1/dir2"));
// String profile_picture = c.getString(TAG_PROFILE_PICTURE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_PROFILE_PICTURE, profile_picture);
// adding HashList to ArrayList
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#SuppressWarnings("resource")
public static String loadImageFromWebOperations(String url, String path) {
try {
InputStream is = (InputStream) new URL(url).getContent();
System.out.println(path);
File f = new File(path);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
try {
byte[] b = new byte[100];
int l = 0;
while ((l = is.read(b)) != -1)
fos.write(b, 0, l);
} catch (Exception e) {
}
return f.getAbsolutePath();
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this.getActivity(), mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME, TAG_PROFILE_PICTURE }, new int[] { R.id.title, R.id.message,
R.id.username ,R.id.imageView1});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(mainViewController.this);
// pDialog.setMessage("Loading Posts...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//pDialog.dismiss();
updateList();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
}
Logcat:
09-08 21:29:01.281: I/System.out(17363): Exc=java.net.MalformedURLException: Protocol not found: profile_picture
09-08 21:29:01.281: W/System.err(17363): org.json.JSONException: No value for null
09-08 21:29:01.321: W/System.err(17363): at org.json.JSONObject.get(JSONObject.java:355)
09-08 21:29:01.321: W/System.err(17363): at org.json.JSONObject.getString(JSONObject.java:515)
09-08 21:29:01.321: W/System.err(17363): at com.rynovation.kline.mainViewController.updateJSONdata(mainViewController.java:128)
09-08 21:29:01.321: W/System.err(17363): at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:230)
09-08 21:29:01.371: W/System.err(17363): at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:1)
09-08 21:29:01.371: W/System.err(17363): at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-08 21:29:01.371: W/System.err(17363): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-08 21:29:01.371: W/System.err(17363): at java.lang.Thread.run(Thread.java:841)
The problem is here
String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(" ", "%20"),sdCard.getAbsolutePath() + "/dir1/dir2"));
First get they value for key and then load the url.

Sending json data into db and display in listview throws "null pointer exception"

I am getting json data from server and i want to pass that data to my db, i want to display those data in my listview,now its thowing some null pointer exception.
Mainactivity.java
public class MainActivity extends ListActivity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final int TAG_CATEGORY = 0;
private static final String CATEGORY_COLUMN_ID = "_id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
// Adding items to listview
/**
* Enabling Search Filter
* */
new GetDataAsyncTask().execute();
//praycount.setOnClickListener(this);
//initView();
}
/*private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
} */
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getProdData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser jsonObject = new JSONParser();
//JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
//JSONArray aJson = jsonObject.getJSONArray(url);
JSONArray Json = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = Json.getJSONArray(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData() {
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}
private void setListAdapter(SimpleCursorAdapter dataAdapter2) {
// TODO Auto-generated method stub
}
It showing error in this line registerForContextMenu(getListView()); it thows null pointer exception.
mycategory.java
public class Category {
String _id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this._id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return _id;
}
public void setId(String id) {
this._id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
this is my db part like this i am giving
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "test";
private static final String DATABASE_TABLE_PROJ = "projects";
private static final int DATABASE_VERSION = 3;
public static final String CATEGORY_COLUMN_ID = "_id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "GinfyDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private final Context mCtx;
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key , "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE_PROJ = "CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER );" ;
db.execSQL(DATABASE_CREATE_PROJ);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
String query = "insert into"+ DATABASE_NAME+ " values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
}
Is it my code is correct to send an json data into an database and show in an listview
Logcat error is
07-05 08:59:57.605: E/AndroidRuntime(30062): FATAL EXCEPTION: main
07-05 08:59:57.605: E/AndroidRuntime(30062): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonandroid/com.example.jsonandroid.MainActivity}: java.lang.NullPointerException
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.os.Handler.dispatchMessage(Handler.java:99)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.os.Looper.loop(Looper.java:137)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread.main(ActivityThread.java:5039)
07-05 08:59:57.605: E/AndroidRuntime(30062): at java.lang.reflect.Method.invokeNative(Native Method)
07-05 08:59:57.605: E/AndroidRuntime(30062): at java.lang.reflect.Method.invoke(Method.java:511)
07-05 08:59:57.605: E/AndroidRuntime(30062): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-05 08:59:57.605: E/AndroidRuntime(30062): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-05 08:59:57.605: E/AndroidRuntime(30062): at dalvik.system.NativeStart.main(Native Method)
07-05 08:59:57.605: E/AndroidRuntime(30062): Caused by: java.lang.NullPointerException
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.Activity.registerForContextMenu(Activity.java:2857)
07-05 08:59:57.605: E/AndroidRuntime(30062): at com.example.jsonandroid.MainActivity.onCreate(MainActivity.java:68)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.Activity.performCreate(Activity.java:5104)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-05 08:59:57.605: E/AndroidRuntime(30062): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
Your class does not extend ListActivity.
registerForContextMenu(getListView());
http://developer.android.com/reference/android/app/ListActivity.html#getListView()
public ListView getListView ()
Get the activity's list view widget.
And you have this which can be removed.
private View getListView() {
// TODO Auto-generated method stub
return null; // returning null
}
You also have this
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
Both refer to the same resource id.
From your comments you say you get
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list
Your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
<ListView
android:id="#android:id/list" // must have this
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
Edit:
public class MainActivity extends ListActivity{// implements FetchDataListener,OnClickListener{
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
fillData(projectsCursor);
}
else
{
new GetDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
fillData(projectsCursor);
}
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData()
{
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.ginfy.com/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("content");
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.textView1, R.id.textView2, R.id.textView3};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}else
{
Log.i("...........","null");
}
}
}
The other change in your DB class
void saveCategoryRecord(Category category) {
/// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_COUNT, category.getCount());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
Extend your activty from ListActivity

Categories

Resources