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

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

Related

Getting json response in log.d but not inside app (code included)

I am trying to use the ProductHunt API to display a list of new posts in a ListView and further expand the list item on click.
On opening the app, the Progress bar appears but after that the app screen stays blank. I think there might be some error in my OnPostExecute method, because when I added a textview to display a string, its getting displayed but my listView is not getting displayed.
I used the standard Apache HttpClient for handling api requests.
I have 4 classes,
MainActivity.java
package com.emoji.apisoup;
/**
* Created by mdhalim on 16/05/16.
*/
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
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.ListView;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
public class MainActivity extends Activity {
private ListView lvPosts;
private ProductHuntAdapter adapterPosts;
public static final String POST_DETAIL_KEY = "posts";
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phunt_main);
String serverURL = "https://api.producthunt.com/v1/posts/";
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts = (ListView) findViewById(R.id.lvPosts);
lvPosts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
{
Intent i = new Intent(MainActivity.this, ProductHuntDetail.class);
i.putExtra(POST_DETAIL_KEY, adapterPosts.getItem(position));
startActivity(i);
}
}
});
new LongOperation().execute(serverURL);
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Content = new DefaultHttpClient();
private String Error = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(String... urls){
JSONArray items = null;
try {
HttpGet httpget = new HttpGet(urls[0]);
httpget.setHeader("Accept","application/json");
httpget.setHeader("Content-Type","application/json");
httpget.setHeader("Authorization","Bearer 2587aa878d7334e3c89794a6b73ebffb59a06c23b82cd0f789d2ab72d2417739");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String jsonStr = Content.execute(httpget, responseHandler);
Log.d("Response: ", "> " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray("posts");
// Parse json array into array of model objects
ArrayList<ProductHuntList> posts = ProductHuntList.fromJson(items);
// Load model objects into the adapter
for (ProductHuntList post : posts) {
adapterPosts.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
}
}
ProductHuntList.java containing the JSON Data model and deserializer and a static method for parsing an array of JSON
package com.emoji.apisoup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntList implements Serializable {
private static final long serialVersionUID = -8959832007991513854L;
private String name;
private String tagline;
private String screenshot_url;
private String largePosterUrl;
private String discussion_Url;
private String created_at;
private int votes_count;
public String getNames() {
return name;
}
public String getCreated_at() {
return created_at;
}
public String getScreenshot_url() {
return screenshot_url;
}
public String getDiscussion_Url() {
return discussion_Url;
}
public int getVotes_count() {
return votes_count;
}
public String getLargePosterUrl() {
return largePosterUrl;
}
public String getTagline(){
return tagline;
}
public static ProductHuntList fromJson(JSONObject jsonObject) {
ProductHuntList b = new ProductHuntList();
try {
// Deserialize json into object fields
b.name = jsonObject.getString("name");
b.created_at = jsonObject.getString("created_at");
b.tagline = jsonObject.getString("tagline");
b.screenshot_url = jsonObject.getJSONObject("screenshot_url").getString("300px");
b.largePosterUrl = jsonObject.getJSONObject("screenshot_url").getString("850px");
b.votes_count = jsonObject.getInt("votes_count");
b.discussion_Url = jsonObject.getString("discussion_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
// Return new object
return b;
}
public static ArrayList<ProductHuntList> fromJson(JSONArray jsonArray) {
ArrayList<ProductHuntList> posts = new ArrayList<ProductHuntList>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productJson = null;
try {
productJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
ProductHuntList post = ProductHuntList.fromJson(productJson);
if (post != null)
{
posts.add(post);
}
}
return posts;
}
}
ProductHuntAdapter.java this implements the ArrayAdapter
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntAdapter extends ArrayAdapter<ProductHuntList> {
public ProductHuntAdapter(Context context, ArrayList<ProductHuntList> aPosts) {
super(context, 0, aPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ProductHuntList posts = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_product_hunt, null);
}
// Lookup view for data population
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView created = (TextView) convertView.findViewById(R.id.created);
TextView tagline = (TextView) convertView.findViewById(R.id.tagline);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
name.setText(posts.getNames());
created.setText("Created On: " + posts.getCreated_at() + "%");
tagline.setText(posts.getTagline());
Picasso.with(getContext()).load(posts.getScreenshot_url()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
and finally, a class implementing the activity for Item Details when a user clicks on any item on the list.
ProductHuntDetail
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class ProductHuntDetail extends Activity {
private ImageView ivPosterImage;
private TextView name;
private TextView discusUrl;
private TextView upvotes;
private TextView tagline;
private TextView created;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_hunt_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
name = (TextView) findViewById(R.id.name);
discusUrl = (TextView) findViewById(R.id.discusUrl);
created = (TextView) findViewById(R.id.created);
upvotes = (TextView) findViewById(R.id.upvotes);
tagline = (TextView) findViewById(R.id.tagline);
// Load movie data
ProductHuntList posts = (ProductHuntList) getIntent().getSerializableExtra(MainActivity.POST_DETAIL_KEY);
loadMovie(posts);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(ProductHuntList posts) {
// Populate data
name.setText(posts.getNames());
upvotes.setText(Html.fromHtml("<b>Upvotes:</b> " + posts.getVotes_count() + "%"));
created.setText(posts.getCreated_at());
tagline.setText(posts.getTagline());
discusUrl.setText(Html.fromHtml("<b>Discussion Url:</b> " + posts.getDiscussion_Url()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(posts.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
I have been trying to debug this for hours :/
Your Async task is returning a void.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
As far as I can tell from the code, aPosts is empty.
I think your Async task should be -
AsyncTask<String, Void, ProductHuntAdapter>
and remove -
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
You are creating and updating this in your doInBackground() method already.
I got it!
I didnt need to declare these lines again in my onPostExecute() method
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
So bascially, my new onPostExecute() method goes like this
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lvPosts.setAdapter(adapterPosts);
}
I had been trying to find this error for last 2 hours, it was harder since, I wasn't even getting any errors. As soon as I posted it on StackOverFlow, seems like I had a divine intervention.

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

ListViewActivity with Custom Adapter doesn' t work

Dear Stackoverflow Comunitiy,
I'd like to have a ListView getting filled by an BackgroundTask.
This is my actual Code
HomeActivity:
package com.example.instaemgnew;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import com.example.instaemgnew.classes.Beitrag;
import com.example.instaemgnew.classes.beitragLoader;
import com.example.instaemgnew.classes.listViewHomeActivitiyAdapter;
public class HomeActivity extends ListActivity {
listViewHomeActivitiyAdapter adapter;
ArrayList<Beitrag> beitraege = new ArrayList<Beitrag>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
setListAdapter(adapter);
Log.e("TestPoint 1", "Adapter Set");
new beitragLoader(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
}
BackgroundTask:
package com.example.instaemgnew.classes;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.instaemgnew.HomeActivity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ArrayAdapter;
public class beitragLoader extends AsyncTask<String, String, String>{
//Array List für die Beiträge
ArrayList<Beitrag> beitraege;
//User Daten
/*mail = userManager.getMail();
grade = String.valueOf(userManager.getGrade());
school = userManager.getSchool();*/
String mail = "simon-frey#gmx.de";
String grade = String.valueOf(334);
String school = "EMG";
//JSONParser
JSONParser jsonParser = new JSONParser();
//ArrayList mit Beitrag Objekten
ArrayList<Beitrag> beitraegeList;
// Onlinedaten
private static final String SERVER_URL = "http://yooui.de/InstaEMGTest/";
private static final String PASSWORD = "8615daf406f7e2b313494f0240";
//Context
private final HomeActivity homeActivity;
//Konstruktor
public beitragLoader(HomeActivity homeActivity){
this.homeActivity = homeActivity;
Log.e("TestPoint 2", "Created beitragLoader");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: Test for InternetConnection
Log.e("TestPoint 3", "PreExectute");
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
beitraegeList = new ArrayList<Beitrag>();
String SQLUrl = SERVER_URL + "testBeiträgeAbrufen.php";
String token = getMD5Hash("password" + "data");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));
//TODO: params.add(new BasicNameValuePair("page", skipBeitraege))
params.add(new BasicNameValuePair("grade", grade));
params.add(new BasicNameValuePair("school", school));
JSONObject json = jsonParser.makeHttpRequest(SQLUrl, "GET", params);
if (json == null) {
// Server offline
}
Log.e("TestPoint 3,5", "FetchedJSON");
try {
JSONArray beitraege = json.getJSONArray("beitraege");
// looping through All Products
for (int i = 0; i < beitraege.length(); i++) {
Beitrag tempBeitrag = null;
Log.e("TestPoint 3,6", "StartLoop");
JSONObject c = beitraege.getJSONObject(i);
//HDImagesURLList ArrayList
ArrayList<String> HDImagesURLList = new ArrayList<String>();
// Storing each json item in variable
String id = c.getString("ID");
String url = c.getString("url");
String titel = c.getString("titel");
String tags = c.getString("tags");
String onlineDate = c.getString("onlineDate");
Log.e("TestPoint 3,7", "Stored JSON Items");
//Fetching previewImage
try {
Log.e("TestPoint 3,8", "TryImageDownload");
InputStream in = new java.net.URL(url).openStream();
String fileName = "InstaEMG" + String.valueOf(System.currentTimeMillis())+".jpg";
Log.e("imageUri", url);
Log.e("fileName", fileName);
FileOutputStream fileOutput = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileName));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = in.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
Log.e("File Output", String.valueOf(bufferLength));
}
//Fill HDImagesURLList
//TODO
// creating newBeitrag
tempBeitrag = new Beitrag(Integer.parseInt(id), titel, onlineDate, fileName, HDImagesURLList);
// adding Beitrag to ArrayList
beitraegeList.add(tempBeitrag);
Log.e("TestPoint 4", "NewBeitragSet");
} catch (MalformedURLException e) {
Log.e("Exceptrion", "URL Exception");
} catch (IOException e) {
Log.e("Exceptrion", "IO Exception");
}
homeActivity.addToListView(tempBeitrag);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
}
/**
* After completing background Safe to MainActivity
* **/
protected void onPostExecute() {
Log.e("TestPoint 5", "PostExecutre");
// homeActivity.updateListView(beitraegeList);
}
/**
* Methode zum Errechnen eines MD5Hashs
*
* #param string
* String welcher kodiert werden soll
* #return MD5 Hash des Strings, bei Fehler der ursprüngliche String.
*/
private String getMD5Hash(String string) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(string.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < result.length; i++) {
if ((0xff & result[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & result[i])));
} else {
hexString.append(Integer.toHexString(0xFF & result[i]));
}
}
string = hexString.toString();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return string;
};
}
and the BaseAdapter:
package com.example.instaemgnew.classes;
import java.util.ArrayList;
import com.example.instaemgnew.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class listViewHomeActivitiyAdapter extends BaseAdapter {
private final Context context;
private ArrayList<Beitrag> beitraege;
private final LayoutInflater layoutInflater;
public listViewHomeActivitiyAdapter(Context context, ArrayList<Beitrag> beitraege) {
super();
this.beitraege = beitraege;
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Allgemeien Layout Vorgaben
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_beitrag_row_layout, parent, false);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.single_beitrag_row_layout, null);
}
//getViews
TextView titelView = (TextView) rowView.findViewById(R.id.beitragTitel);
ImageView beitragImageView = (ImageView) rowView.findViewById(R.id.beitragImg);
/*
* TODO: Tags anzeigen und suchen lassen (Wunschfunktion)
* TextView tagsView = (TextView) rowView.findViewById(R.id.beitragTags);
*/
//setTitel From Object
titelView.setText(beitraege.get(position).getTitel());
//setPreviewImage From Object
beitragImageView.setImageBitmap(beitraege.get(position).getPreviewImage());
//setOnClickListener on PreviewImage for PopOutGallery
beitragImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//TODO: PopOut Gallery
}
});
return rowView;
}
#Override
public int getCount() {
return beitraege.size();
}
#Override
public Object getItem(int position) {
return beitraege.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
In my opinion the Bug have to be in the BaseAdapter, but I don't know where it could be.
Sincerly and thankful,
Simon
To fill listView in doInBackground you need to use Handler, or runOnUiThread, because this is not UI thread.
homeActivity.runOnUiThread(new Runnable()
{
public void run()
{
homeActivity.addToListView(tempBeitrag);
}});
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
beitraege is not populated with any data.
Edit:
Instead of calling this from doInbackground. Use a Interface as a call back to the activity and then populate listview.
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
How do I return a boolean from AsyncTask?
Instead of boolen value its arraylist in your case.
Then use the below and set the adapter your listview
adapter = new listViewHomeActivitiyAdapter(this, beitraege);

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.

android linkify in listview

I have this code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.romantic.aacplay.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
// import android.text.Html;
// import android.text.Html;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class PodCast extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
private static String url_all_products = "http://mysite.net/andro/pcast.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "podcast";
private static final String TAG_LINK = "link";
private static final String TAG_NAME = "nume";
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poadcast);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Color.RED,Color.BLACK});
View title = getWindow().findViewById(android.R.id.title);
View titleBar = (View) title.getParent();
titleBar.setBackgroundDrawable(gd);
productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PodCast.this);
pDialog.setMessage("Se incarca. Asteapta...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("Ultimele 10 piese: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String link = c.getString(TAG_LINK);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// String href = String.format(" %s ", link, name);
// String cici = Html.fromHtml(href).toString();
map.put(TAG_NAME, name);
map.put(TAG_LINK, "" + Html.fromHtml(link));
// map.put(TAG_LINK, link);
productsList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
}
}
}
Now i'm trying to figure out how can i make the links in listview clickable. I`m trying to linkify a textview that is in found here:
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
}
R.layout.list_item which is a different .xml layout for the listview.
So can you guys help me solve this? Thanks in advance!
I feel instead of using SimpleAdapter,Please extend the BaseAdapter and make the textview you are using as linkify.so it will automatically get click.
please refer:
Android dev blog
put this line to ur textview
android:autoLink="web"
i hope this will solve ur query
I wanted as well to create a linkeable textView on my list adapter so I used:
Linkify.addLinks(textViewLocationPhone, Linkify.PHONE_NUMBERS);
textViewLocationPhone.setLinksClickable(true);
and it worked.

Categories

Resources