Working tweet parser but with empty results - android

My task is to create app that could get latest tweets from x account.
Here is my code what I've made. However I get result (more than 0) only if i set (as search string) my account name. Otherwise I get nothing. Could someone explain me why? I will appreciate for any help.
private ListView lv;
private EditText et;
private ArrayAdapter<String> adapter;
String[] values;
private Token token = null;
private Credential c = null;
private UserAccountManager m = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
et = (EditText) findViewById(R.id.editText1);
et.setText("twapime");
doRest();// first run, initialization, first search
}
private void doRest() {
initAccount();
initSearching();
}
private void initSearching() {
ArrayList<String> listax = getSearchResults(et.getText().toString());
initListViewAdapter(listax);
}
private void initListViewAdapter(ArrayList<String> listax) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listax);
lv.setAdapter(adapter);
}
private void initAccount() {
token = new Token("xxxx",
"xxxx");
c = new Credential("xxxx",
"xxxx", token);
m = UserAccountManager.getInstance(c);
}
private ArrayList<String> getSearchResults(String userTwitter) {
ArrayList<String> lista = new ArrayList<String>();
try {
if (m.verifyCredential()) {
SearchDevice sd = SearchDevice.getInstance();
Query q1 = QueryComposer.from(userTwitter);
Tweet[] ts = sd.searchTweets(q1);
System.out.println(ts.length);
for (int i = 0; i < ts.length; i++) {
lista.add(ts[i].getString(MetadataSet.TWEET_CONTENT));
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (LimitExceededException e) {
e.printStackTrace();
}
return lista;
}
public void btnSearcher(View w) {//OnClickListener
initSearching();
}

I think it happens when someone block public information data for untrusted user.

Related

How to populate a ListView with Parse Array using ArrayAdapter

So I'm new to Android and I'm using Parse as my backend. I have an Array column in Parse called PrescriptionArray. I want to take the contents of this array (String values) and populate a listView with them. I think I'm only missing a couple of lines but not sure where? Any help would be greatly appreciated.. Thanks in advance!
public class PrescriptionsArrayActivity extends AppCompatActivity {
private ListView lvPrescriptions;
private EditText etMedicalID;
private ArrayAdapter<String> adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prescriptions_array);
lvPrescriptions = (ListView) findViewById(R.id.lvPrescriptions);
etMedicalID = (EditText) findViewById(R.id.etMedicalID);
//Get the Medical ID number from previous activity
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("MedicalID");
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
etMedicalID.setText(str);
final List<String> arrayprescription = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(PrescriptionsArrayActivity.this, android.R.layout.simple_list_item_1, arrayprescription);
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PrescriptionObject");
query.whereEqualTo("MedicalID", etMedicalID.getText().toString());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> prescriptionList, ParseException e) {
if (e == null) {
for (int i = 0; i < prescriptionList.size(); i++) {
ParseObject p = prescriptionList.get(i);
if (p.getList("PrescriptionArray") != null) {
String s = arrayprescription.toString();
adapter.addAll(Arrays.asList(s));
}
}
lvPrescriptions.setAdapter(adapter);
}
}
});
}
}

ZygoteInit$Method error in Fragment's onActivityCreated

I have a fragment, and I want to load up the listview in a particular way from my sql lite database:
private ProductDbAdapter mDbHelper;
private ProductListAdapter productAdapter;
private View mView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Open Database Connection
mDbHelper = new ProductDbAdapter(getActivity());
try {
mDbHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
// Setup list view
productAdapter = new ProductListAdapter(getActivity(), R.layout.product_row);
ListView lv = (ListView) mView.findViewById(R.id.lvProducts);
lv.setAdapter(productAdapter);
Cursor productCursor = mDbHelper.fetchAll();
getActivity().startManagingCursor(productCursor);
int numProducts = productCursor.getCount();
for(int i =0; i< numProducts; i++) {
Product prdt = new Product();
// The line below is where it throws an exception //
prdt.Name = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_NAME));
prdt.type = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_TYPE));
String strDate = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_EXPDATE));
// format into local date/time format
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
prdt.dateExpires = sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
// Add to custom adapter
productAdapter.add(prdt);
productCursor.moveToNext();
}
}
Whenever I do this, It stalls on the first reference to the SQLLite Data. It says "com.android.internal.os.ZygoteInit$MethodAndArgsCaller" is the error. I've never gotten this before and I have no clue why this line would cause it since the activity is already created and started. What can I do to fix this?

SimpleCursorAdapter ListView created by messagehandler

I've read through all posts I can find about simplecursoradapter and listview but I still can't seem to find the answer to my problem.
I have an Activity which contains a number of radio buttons, a button and a listview. The Activity first makes an http request to a web server to retrieve some data. The data from the server is written to the sqlite db on the device. Once data has been written to the db, the Activity regains control and creates a Cursor from the db, a SimpleCursorAdapter and sets the adapter as the listview adapter. All data is written ok to the db, I have looped through the elements in the cursor and it contains all expected elements, still no elements is displayed in my listview.
Activity.java:
public class MyActivity extends Activity {
private RadioButton rb1, rb2;
private Button addBut;
private ListView lv;
private LinearLayout statusLayout;
private ScrollView scroll;
private String username;
private DBHelper db;
private Cursor cursor;
private static final String userfk = "1";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
rb1 = (RadioButton)findViewById(R.id.rb1);
rb1.setChecked(true);
rb2 = (RadioButton)findViewById(R.id.rb2);
addBut = (Button)findViewById(R.id.addButton);
statusLayout = (LinearLayout)findViewById(R.id.statusLayout);
scroll = (ScrollView)findViewById(R.id.configscroll);
lv = (ListView)findViewById(R.id.profilesll);
//get data from server, made in asynchtask
getData();
}
MessageHandler called from AsynchTask code:
private class MyHandler extends Handler {
public MyHandler() {
}
public void handleMessage(Message msg) {
final Bundle b = msg.getData();
if (b.getString("result").equalsIgnoreCase(MyResult.ERROR) || b.getString("result").equalsIgnoreCase(MyResult.FAIL)) {
//Handle error
} else {
handleList();
statusLayout.setVisibility(View.GONE);
scroll.setVisibility(View.VISIBLE);
}
}
}
private void handleList() {
if (db == null) {
db = new DBHelper(this);
}
if (cursor == null) {
try {
cursor = db.getListCursor(userfk);
} catch (Exception e) {
err = e.getMessage();
}
if (cursor == null) {
Toast.makeText(MyActivity.this, err != null ? err : getResources().getString(R.string.myerror), Toast.LENGTH_LONG).show();
} else {
try {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] {DBHelper.COLUMN_ID}, new int[] {android.R.id.text1});
lv.setAdapter(adapter);
} catch (RuntimeException e) {
Log.e("test", e.getMessage());
} catch (Exception e) {
Log.e("test", e.getMessage());
}
}
}
}
DBHelper class
public Cursor getListCursor(String userfk) throws Exception {
StringBuilder builder = new StringBuilder("select name as _id from mytable where userfk=?");
List<String> values = new ArrayList<String>();
values.add(userfk);
try {
return this.getReadableDatabase().rawQuery(builder.toString(), values.toArray(new String[values.size()]));
} catch (Exception e) {
Log.d("test", e.getMessage());
throw e;
}
}
I hope someone can give me a hint about what I'm doing wrong! Thanks for your help!

Async Task in android not working

This is a follow up question from my question thread exiting error in android
I created an async task but the values do not show up in the list view....
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
// TODO Auto-generated method stub
Toast.makeText(this, "u clicked " + listItems.get(position) ,Toast.LENGTH_LONG).show();
}
public void getInfo(){
DownloadInfo task = new DownloadInfo();
task.execute(new String[] { "http://www.vogella.de" });
}
private class DownloadInfo extends AsyncTask<String, Void , ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(String ... strings) {
ArrayList<String> listItems1;
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems1 = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"URL"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
if ( driver.getString("DATABASE ERROR").equals("False")){
int length = Integer.parseInt( driver.getString("length"));
Log.i(TAG,"length is " + length);
for( int i =0 ; i< length ; i++){
String info = driver.getString(Integer.toString(i));
String[] array = info.split(",");
Log.i(TAG,"array is " + Arrays.toString(array));
Log.i(TAG,"Date "+ array.length);
Log.i(TAG,"DONE WITH THE LOOP");
//listInfo.add(item);
Log.i(TAG,"Date is"+array[0]);
listItems1.add(array[0]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems1.add("No driver rides created");
}
return listItems1;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.notifyDataSetChanged();
}
}
}
The problem is that the values in the adapter do not get modified...
You initialize your adapter with a empty listItems, after your fill your listItems in AsyncTask. onPostExecute(), your adapter is not get updated, try this:
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.addAll(ListItems);
adapter.notifyDataSetChanged();
}
Hope that help.
listItems = result; won't work, you need to use :
listItems.clear();
listItems.addAll(result);
If you create another list, your adapter won't know it, because it keeps a reference to the old list (which remains the same).

Android HTML Parser Example

I was looking into many HTML parser for android. I tried many libraries. Can anyone please show me an example how to do it. I want to extract the content of each tag. Please help. I am stuck with this.
Please look at this list. Actually, it's lots of options outside there. For instance, I chose HtmlCleaner library for implementation. Below is an example of usage:
Project structure:
Actual source code:
public class HtmlHelper {
TagNode rootNode;
public HtmlHelper(URL htmlPage) throws IOException
{
HtmlCleaner cleaner = new HtmlCleaner();
rootNode = cleaner.clean(htmlPage);
}
List<TagNode> getLinksByClass(String CSSClassname)
{
List<TagNode> linkList = new ArrayList<TagNode>();
TagNode linkElements[] = rootNode.getElementsByName("a", true);
for (int i = 0; linkElements != null && i < linkElements.length; i++)
{
String classType = linkElements[i].getAttributeByName("class");
if (classType != null && classType.equals(CSSClassname))
{
linkList.add(linkElements[i]);
}
}
return linkList;
}
}
public class StackParser extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.parse);
button.setOnClickListener(myListener);
}
private ProgressDialog pd;
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
pd = ProgressDialog.show(StackParser.this, "Working...", "request to server", true, false);
new ParseSite().execute("http://www.stackoverflow.com");
}
};
private class ParseSite extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... arg) {
List<String> output = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("question-hyperlink");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return output;
}
protected void onPostExecute(List<String> output) {
pd.dismiss();
ListView listview = (ListView) findViewById(R.id.listViewData);
listview.setAdapter(new ArrayAdapter<String>(StackParser.this, android.R.layout.simple_list_item_1 , output));
}
}
}

Categories

Resources