Android ActivityThread error - java

I cannot figure out what is causing this Thread error. Here is my code. I commented out almost all the code and it still won't work:
package com.dd.relay;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We'll define a custom screen layout here (the one shown above), but
// typically, you could just use the standard ListActivity layout.
setContentView(R.layout.activity_main);
//ListView lv = (ListView)this.findViewById(R.id.relaylist);
// Make a GET request for data
/* String url = "http://localhost.com/contacts";
String res = null;
try {
HttpRequest request = new HttpRequest();
request.execute(new URL(url));
Log.v(EXTRA_MESSAGE, res);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
String[] from = new String[] {"First", "Last", "Number"};
int[] to = new int[] {R.id.first, R.id.last, R.id.number};
// Create list for contacts
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> temp = new HashMap<String, String>();
int id = 0;
while(id<10)
{
RelayContact contact = new RelayContact("Matt", "Hintzke", "2062259311", id);
temp.put("First",contact.first);
temp.put("Last", contact.last);
temp.put("Number", contact.num);
data.add(temp);
id++;
}
ListAdapter adapter = new SimpleAdapter(this, data, R.layout.list, from, to); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
lv.setAdapter(adapter);
*/
// CharSequence msg = "List loaded";
// Context context = this.getApplicationContext();
//Toast mytoast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
//mytoast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is the error from the console
[2013-07-20 19:18:36 - ddms] null
java.lang.NullPointerException
at org.eclipse.debug.internal.ui.DebugUIPlugin.launchInBackground(DebugUIPlugin.java:1286)
at org.eclipse.debug.ui.DebugUITools.launch(DebugUITools.java:753)
at com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController.debugRunningApp(AndroidLaunchController.java:176)
at com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController.clientChanged(AndroidLaunchController.java:1733)
at com.android.ddmlib.AndroidDebugBridge.clientChanged(AndroidDebugBridge.java:912)
at com.android.ddmlib.Device.update(Device.java:591)
at com.android.ddmlib.Client.update(Client.java:868)
at com.android.ddmlib.HandleWait.handleWAIT(HandleWait.java:88)
at com.android.ddmlib.HandleWait.handleChunk(HandleWait.java:66)
at com.android.ddmlib.MonitorThread.callHandler(MonitorThread.java:414)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:322)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)

Related

Connect to MySQL?

I used this code to connect to MySQL using WAMP.
But it doesn't work
package com.first.ismael.material_drawer;
import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by ismae_000 on 11/20/2015.
*/
public class all_meals extends Fragment {
public ProgressDialog pDialog ;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// url to get all products list
private static String url_all_products = "http://192.168.1.7/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "component";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_TYPE ="type";
ListView lv;
// products JSONArray
JSONArray products = null;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.all,
container, false);
productsList = new ArrayList<HashMap<String, String>>();
lv = (ListView)view.findViewById(R.id.listView2);
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// 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);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Toast.makeText(getActivity(),"There is nothing",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_NAME},
new int[]{R.id.pid, R.id.name});
// updating listview
lv.setAdapter(adapter);
}
});
}
}
}
I used it in a Fragment.
Please help
If you are using WAMP means using localhost for database MySql. Ip address for localhost should 10.0.2.2 not 192.168.1.7
try to replace
_http://192.168.1.7/get_all_products.php
with
_http://10.0.2.2/get_all_products.php
and check your output get_all_products.php, that's should be json format
read this
- why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client
check json format use this
- _http://jsonlint.com

android.content.res.Resources$NotFoundException: String resource ID #0x2

This is ma java code which gets data from json object
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OutboxActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> outboxList;
/*************************************************************************************************/
List<String> too = new ArrayList<String>();
List<String> sub = new ArrayList<String>();
List<String> datel = new ArrayList<String>();
/**********************************************************************/
// products JSONArray
JSONArray outbox = null;
// Outbox JSON url
private static final String OUTBOX_URL = "http://www.bitfutura.in/outbox123.json";
// ALL JSON node names
private static final String TAG_MESSAGES = "messages";
private static final String TAG_ID = "id";
private static final String TAG_TO = "to";
private static final String TAG_SUBJECT = "subject";
private static final String TAG_DATE = "date";
SQLiteDatabase dbs;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbs=openOrCreateDatabase("mycar.db",MODE_PRIVATE,null);
dbs.execSQL("create table if not exists Outbox(id varchar,top varchar,subject varchar,messsage" +
" varchar,date varchar)");
// Hashmap for ListView
outboxList = new ArrayList<HashMap<String, String>>();
// Loading OUTBOX in Background Thread
new LoadOutbox().execute();
}
/**
* Background Async Task to Load all OUTBOX messages by making HTTP Request
* */
class LoadOutbox extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OutboxActivity.this);
pDialog.setMessage("Loading Outbox ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Outbox JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(OUTBOX_URL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Outbox JSON: ", json.toString());
try {
outbox = json.getJSONArray(TAG_MESSAGES);
// looping through All messages
dbs.execSQL("DELETE FROM Outbox");
for (int i = 0; i < outbox.length(); i++) {
JSONObject c = outbox.getJSONObject(i);
/***************************************************/
/************************************************/
// Storing each json item in variable
String id = c.getString(TAG_ID);
String to = c.getString(TAG_TO);
String subject = c.getString(TAG_SUBJECT);
String date = c.getString(TAG_DATE);
/****************************************************************/
too.add(to);
sub.add(subject);
datel.add(date);
/*********************************************************************/
String shu="'"+id+"','"+to+"','"+subject+"','"+date+"','"+date+"'";
dbs.execSQL("insert into Outbox values("+shu+")");
// subject taking only first 23 chars
// to fit into screen
if(subject.length() > 23){
subject = subject.substring(0, 22) + "..";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TO, to);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
outboxList.add(map);
}
} 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 products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
String[] toa = new String[too.size()];
toa = too.toArray(toa);
String[] suba = new String[sub.size()];
suba = sub.toArray(suba);
String[] datea = new String[datel.size()];
datea = datel.toArray(datea);
/*
ListAdapter adapter = new SimpleAdapter(
OutboxActivity.this, outboxList,
R.layout.outbox_list_item, new String[] { TAG_SUBJECT, TAG_TO, TAG_DATE },
new int[] { R.id.subject, R.id.to, R.id.date });
// updating listview
setListAdapter(adapter);
*/
EventAdapter adapter=new EventAdapter(OutboxActivity.this,toa,suba,datea);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
try {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int Slecteditem = position;
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
}
});
}catch(Exception ae)
{
Toast.makeText(getApplicationContext(),ae.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
}
This is my Event adapter class
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EventAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private final String[] itemname2;
private final String[] itemname3;
public EventAdapter(Activity context, String[] itemname,String[] itemname3,String[] itemname2) {
super(context, R.layout.myevent, itemname);
// TODO Auto-generated constructor stub
this.context=context;
this.itemname=itemname;
this.itemname3=itemname3;
this.itemname2=itemname2;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.myevent, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
TextView extratxt1 = (TextView) rowView.findViewById(R.id.textView1);
TextView extratxt2 = (TextView) rowView.findViewById(R.id.textView2);
txtTitle.setText(itemname[position]);
extratxt1.setText(itemname2[position]);
extratxt2.setText(itemname3[position]);
return rowView;
};
}
This is my Activitymain xml code for list view
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
The list view successfully get gets updated but when i click an option in list view that shows up an toast,the position i clicked it shows an error
android.content.res.Resources$NotFoundException: String resource ID #0x2
at android.content.res.Resources.getText(Resources.java:274)
at android.widget.Toast.makeText(Toast.java:277)
at com.dk.sample.folder.residemenu.OutboxActivity$LoadOutbox$1$1.onItemClick(OutboxActivity.java:200)
at android.widget.AdapterView.performItemClick(AdapterView.java:300)
at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
at android.widget.AbsListView.onTouchUp(AbsListView.java:3845)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3617)
at android.view.View.dispatchTouchEvent(View.java:8388)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2424)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2158)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2314)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1692)
at android.app.Activity.dispatchTouchEvent(Activity.java:2739)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2275)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
int Slecteditem = position;
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
You are using the item position for the message argument. Toast doesn't know about your adapter and thinks you are giving it a string resource ID, but fails to find a string with that ID (in this case 2). You either need to use an actual string resource id, or an actual String.
Since your adapter extends ArrayAdapter, you could use adapter.getItem(position) instead (which I suspect is what you intended to do).

How should I switch to new activity from a listview that contains an array of data?

I want to switch to a new activity from the listview that contains an array of data from a mysql database?
File: TampilGambarActivity.java
package com.tes.menu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
//import android.content.Intent;
import android.os.Bundle;
//import android.view.View;
import android.widget.ListView;
//import android.widget.Toast;
public class TampilkanGambarActivity extends Activity {
static String in_idmenu = "id_menu";
static String in_jenismenu = "jenis_menu";
static String in_image_menu = "image_menu";
JSONArray str_json = null;
public String lo_Koneksi,isi ;
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> data_map = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Koneksi lo_Koneksi = new Koneksi();
isi = lo_Koneksi.isi_koneksi();
String link_url = isi+"menu.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
str_json = json.getJSONArray("menu");
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String id_menu = ar.getString("id_menu");
String image_menu = ar.getString("image_menu");
String jenis_menu = ar.getString("jenis_menu");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_idmenu, id_menu);
map.put(in_image_menu, image_menu);
map.put(in_jenismenu, jenis_menu);
data_map.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, data_map);
list.setAdapter(adapter);
}
}
Set your Listview on Item Click Listener
listView.setOnItemClickListener(this);
The method should look like this.
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//you can send data here based on the position
}
Of course let the class implement the listener, and then within the onItem click use the Intent
Intent intent = new Intent(this, LazyAdapter.class);
intent.putExtra("hashMap", map);
startActivity(intent);
Get the data from the Second activity
Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("hashMap");
Now you have the data in the second activity, use it the same way.

Error parsing JSON Array, DOCTYPE

ive got a working listview which receives JSON from my DB. But when i try with this link: I get "Error parsing data org.json.JSONException: Value
The JSON output is clean and should work! My activitiy
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListShowsController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Shows");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("video_id", String.valueOf(i));
map.put("video_title", "" + e.getString("video_title"));
//map.put("season", "Season: " + e.getString("season"));
map.put("video_location", "" + e.getString("video_location"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListShowsController.this,
ShowsController.class);
myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
AsyncTask
package com.spxc.ssa.streaming.task;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class JsonAsync extends AsyncTask<String, Void, JSONObject> {
public interface JsonListener {
public void onObjectReturn(JSONObject object);
}
public void setJsonListener(JsonListener jsonListener) {
mListener = jsonListener;
}
private JsonListener mListener;
public static final String TAG = JsonAsync.class.getSimpleName();
#Override
protected JSONObject doInBackground(String... params) {
// The argument passed into tasks are arrays. So you can pass 0 or more
// arguments, when calling from activity, it's really up to you. They
// just have to be separated by commas. Like this :
// new JsonAsync.execute("thisUrl", "thatUrl", "anotherUrl");
// Although I am only grabbing the first item in the array, by calling
// params[0] below.
JSONObject object = null;
if (params != null && params.length > 0) {
object = JSONfunctions.getJSONfromURL(params[0]);
} else {
Log.e(TAG, "Task needs an argument to be able to retrieve data.");
}
// I return the item out of this method, because it is happening of the
// UI thread, so it can;t update items on the screen. You can work with
// a database from this method. That is actually recommended.
return object;
}
#Override
protected void onPostExecute(JSONObject result) {
// This method can touch UI components without throwing an error.
if (result != null && mListener != null) {
mListener.onObjectReturn(result);
}
super.onPostExecute(result);
}
}
I've never seen this error before! What is the problem?
Any help is much appreciated ! Thanks
EDIT:
My other activity which works:
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListMoviesController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Movies");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://strongpixel.com/java/movies.php");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("name"));
//map.put("date", "Released: " + e.getString("date"));
map.put("path", "" + e.getString("path"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "name", "path" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListMoviesController.this,
MoviesController.class);
myIntent.putExtra("name", o.get("name"));
myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("path", o.get("path"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Logcat:
03-12 08:35:18.722: E/log_tag(25208): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-12 09:06:52.877: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:52.920: V/CustomViewAbove(26397): onInterceptTouch moved to:(30.26232, 662.0), diff:(29.26232, 1.0), mLastMotionX:1.0
03-12 09:06:52.936: V/CustomViewAbove(26397): onInterceptTouch moved to:(73.95948, 663.08905), diff:(72.95948, 0.08905029), mLastMotionX:1.0
03-12 09:06:52.940: V/CustomViewAbove(26397): this slide allowed true dx: 72.95948
03-12 09:06:52.940: V/CustomViewAbove(26397): Starting drag! from onInterceptTouch
03-12 09:06:52.993: V/SlidingMenu(26397): changing layerType. hardware? true
03-12 09:06:53.229: V/SlidingMenu(26397): changing layerType. hardware? false
03-12 09:06:54.214: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:54.450: D/dalvikvm(26397): GC_CONCURRENT freed 73K, 7% free 4495K/4812K, paused 3ms+6ms, total 24ms
03-12 09:06:55.025: E/log_tag(26397): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Edit:
I tried the same JSON, but just in a txt file strongpixel.com/java/JSON.txt, this works without any problem, it takes some time to load, but it works.
You can't get it work cause your code can't load proper JSON String. There is only one place where you make download:
JSONfunctions.getJSONfromURL(params[0])
You get the obvious error: JSON object can't be created from string like <!doctype html>. It means that you download HTML data instead of JSON. For simple test you can try next code and you will get the same error:
JSONObject object = new JSONObject("<!DOCTYPE html>");
You can get this wrong response from numerous reasons: wrong request, your fire wall, proxy, even server might return wrong result if you don't specify User-Agent header or doesn't perform authorization. I do recommend using some web debug tools that will help you to handle such situations and make sure that your app receive valid data.
If you are using Windows i would recommend you to use Fiddler, it is free. Here is example how you can setup fiddler for your test device: http://www.cantoni.org/2011/06/28/debug-http-android-fiddler
Anyway there is alternative tools for other operating system.
I got it working! It was a simple and idiotic mistake. The server i was connecting to didnt allow POST so in the adapter i changed Httppost to Httpget

Errors in Android project

I'm having problems working my way through an old tutorial, essentially i'm trying to pull the data returned in JSON format from www.amazingjobs.co.uk/app/marc/api/candidates/ into a listview.
I literally started learning android/java 24 hours ago so its likely it may be very simple but I just can't quite seem to figure it out, lines with errors are in bold!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.google.gson.Gson;
public class Searchjobs extends Activity {
// url to make request
private static String url = "http://www.amazingjobs.co.uk/app/marc/api/candidates/";
// JSON Node names
private static final String TAG_RESULTS = "results";
// Jobs JSONArray
JSONArray jobs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchjobs);
Button Searchbutton = (Button) findViewById(R.id.Searchbutton);
Searchbutton.setOnClickListener(searchClick);
}
private OnClickListener searchClick = new OnClickListener() {
public void onClick(View v) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> JobList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl("http://www.amazingjobs.co.uk/app/marc/api/candidates/");
// Getting Array of Contacts
try {
jobs = json.getJSONArray(TAG_RESULTS);
for(int i = 0; i < jobs.length();i++){
JSONObject j = jobs.getJSONObject(i);
String title = j.getString("job_title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Title", title);
JobList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**ListAdapter adapter = new SimpleAdapter(this, JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});**
**ERROR: The constructor SimpleAdapter(new View.OnClickListener(){}, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined**
**setListAdapter(adapter);
The method setListAdapter(ListAdapter) is undefined for the type new View.OnClickListener(){}**
// selecting single ListView item
**ListView lv = getListView();**
**ERROR: The method getListView() is undefined for the type new View.OnClickListener(){}**
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
};
};
EDIT Ok new code is below, errors are, which seems odd because the activity errors relate to an activity that definately exists, have tried restart/clean in eclipse too.
Description Resource Path Location Type
activity_searchjobs cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 47 Java Problem
activity_searchjobs cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 105 Java Problem
Searchbutton cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 48 Java Problem
list_item cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 83 Java Problem
public class Searchjobs extends ListActivity {
// url to make request
private static String url = "http://www.amazingjobs.co.uk/app/marc/api/candidates/";
// JSON Node names
private static final String TAG_RESULTS = "results";
// Jobs JSONArray
JSONArray jobs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchjobs);
Button Searchbutton = (Button) findViewById(R.id.Searchbutton);
Searchbutton.setOnClickListener(searchClick);
}
private OnClickListener searchClick = new OnClickListener() {
public void onClick(View v) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> JobList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl("http://www.amazingjobs.co.uk/app/marc/api/candidates/");
// Getting Array of Contacts
try {
jobs = json.getJSONArray(TAG_RESULTS);
for(int i = 0; i < jobs.length();i++){
JSONObject j = jobs.getJSONObject(i);
String title = j.getString("job_title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Title", title);
JobList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(getApplication(), JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
};
};
You need to extend ListActivity not Activity to make methods like getListView() avaialable or just replace it with findViewById() if you do not want to use ListActivity (it's not mandatory).
ListAdapter adapter = new SimpleAdapter(this, JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
should be changed to:
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
Second,
ListView lv = getListView();
will be resolved if you extend ListActivity instead of Activity.

Categories

Resources