Storing a spinner item in a string value - java

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

Related

the application has stopped, when i tried to clear all data

i tried to clear all data from the table inside my database, it was successfull, but the only problems is, everytime i pressed the clear button, it does clear all data but after that the application shows it has stopped
which part did i go wrong? below is my coding from my database:
public boolean deleteRow(long id) {
SQLiteDatabase db = helper.getWritableDatabase();
String where = data.UID + "=" + id;
return db.delete(data.TABLE_NAME, where, null) != 0;
}
public void DeleteAll(){
Cursor c = readEntry();
long id = c.getColumnIndexOrThrow(data.UID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) id));
} while (c.moveToNext());
}
c.close();
return;
}
and code from the other java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showbmi);
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
bb = (Button)findViewById(R.id.bb);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
data = new fitnessdatabase(this);
BuildTable();
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.DeleteAll();
new MyAsync().execute();
}
});
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
table_layout.removeAllViews();
PD = new ProgressDialog(Showbmi.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
String weight = weightinputid.getText().toString();
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String date1 = mDateText.getText().toString();
// inserting data
data.open();
// sqlcon.insertData(firstname, lastname);
long id = data.insertData(weight, bmi, status, date1);
BuildTable();
return null;
}
}
the error from the logcat as shown below:
java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.example.adiehabs.fitnessku.Showbmi$MyAsync.doInBackground(Showbmi.java:188)
at com.example.adiehabs.fitnessku.Showbmi$MyAsync.doInBackground(Showbmi.java:169)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
When you try data.Open() it hits an uninitialised variable as you've initalised it in a private void. Change it to public or put all that code into your created bundle. As the UI controls will also be null.
edit your updated with logcat confirms this. In the do in background.
Caused by: java.lang.NullPointerException
at com.example.adiehabs.fitnessku.Showbmi$MyAsync.doInBackground(Showbmi.java:188)
private void initializeApp(){
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) id));
} while (c.moveToNext());
}
I would use:
Move the cursor to first and only move it if it's not gone past the last item.
c.moveToFirst();
while(!c.isAfterLast()) {
deleteRow(c.getLong((int) id));
c.moveToNext();
}
}
The other thing:
Have you declared these variables in your main scope table_layout, PD?
The app not responding is often from a nullpointer exception.
Delete all table rows
public boolean deleteTable(){
return mSQLiteDatabase.delete(DataBaseHelper.TABLE, null, null) > 0;
}

search filter for Listview [duplicate]

I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}

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");}
}

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

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);

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.

Categories

Resources