[Q] Please help with tutorial code! - Android Software Development

Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!

ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.

Related

[RESOLVED] [Q] Linking list positions with android market pages

Hey guys,
I need some help with my first app.
I want to link some list positions to the respective android market pages. My current code looks like this:
Code:
package com.asm.reader;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class TitlesActivity extends ListActivity {
/** Called when the activity is first created. */
String[] links = {
"Get Full Version", "Get Reading Sample 2", "Get Reading Sample 3", "Get Reading Sample 4", "Get Reading Sample 5",
"Get Story 2", "Get Story 3", "Get Story 4", "Get Story 5"};
private ArrayAdapter<String> adapter;
private String selectedItem;
private final Context context = this;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnItemClickListener itemListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
}
};
ArrayList<String> list = new ArrayList<String>(Arrays.asList(links));
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
list);
setListAdapter(adapter);
getListView().setOnItemClickListener(itemListener);
}
}
The dev guide says I have to do this:
Code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.android.example"));
startActivity(intent);
But how do I set it with the right position?
Thanks a lot in advance, I hope you guys can help me out a little bit.
----
edit: I got it .
mind sharing your solution so that if someone is searching for a similar topic they can see how you solved it and not just that you did
thanks

Android App Posting to HTTP

Alright so, this may get a bit confusing so feel free to ask me what the hell I'm talking about.
I am developing and app to run along side of a PHP web panel that is in development. I've been searching around for a way to hand logins on the app. The best method I could find that appears to suite our needs is to POST to HTTP. However while setting up the login file based on a tutorial I found, it doesn't seem to pull the data back properly. We are using a mysql database however we recently revamped the site and moved from mysql_query to PDO statements(not sure if that has anything to do with it).
Anyways what currently happens is you click login it checks the page and returns false all the time, unless the word "true" is echo'ed.
Here is my current code on the app side:
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity implements OnClickListener{
Button ok,back,exit;
TextView result;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ok = (Button)findViewById(R.id.button_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.login_text);
}
public void postLoginData(){
new Thread(new Runnable(){
public void run(){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try
{
EditText uname = (EditText)findViewById(R.id.usernamelogin);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.passwordlogin);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("submit", "login"));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("TMCP", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("TMCP", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("TMCP", "TRUE");
}
else
{
Log.w("TMCP", "FALSE");
}
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
}).start();
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
[user=439709]@override[/user]
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
Is there another way I should go about tackling this project? Besides logins I'm going to need the app to pull results from the database to create Lists, and Various other functions.
Thanks in advance for the help.
JakeR
I believe you're on the right track - this is how I implemented client-server communications in my app.
For transferring more complex data, I would recommend using PHP to print JSON arrays containing the data. Your app can then simply parse it to extract the data. You'd essentially be making your own 'api'.
Finally, when debugging your PHP scripts, I'd recommend you check out the postman rest client - it's powerful and makes developing 100x faster. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
I hope that answered your question, please feel free to ask anything!
Sent from my LG-P500 using xda app-developers app
I have done exactly the same thing with my forum viewing app. You have to post all data required, also any hidden input for example. Are you sure you posted all inputs?
I agree with the response above to use JSON format to obtain data as it is extremely easy and fast to use.
Sent from my NexusHD2 using xda app-developers app
When you use JSON the gson library from Google is a great help.

Webview Fragments and back button

I am having trouble using the back button to go back in webview. I have 5 different fragments in a tab + swipe layout. Each having a different webview. I have my MainActivity.Java as well as a java file for each fragment. Using the examples shown in stackoverflow regarding this (can't link. Sorry) I get a force close whenever I press back on the app. So I received some helped and did a non-conventional stab at it but I get a couple of errors so I'm hoping one of you guys can help me out. I am super new to app development and java in general so please bear with me.
Here is my MainActivity.java where the errors are:
Code:
package com.-------;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
[user=439709]@override[/user]
public void onBackPressed(){
mSectionsPagerAdapter.getLastFragment().tryGoBack(); [B]<-Error #1[/B]
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private WebViewFragment lastFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public WebViewFragment getLastFragment() {
return lastFragment;
}
[user=439709]@override[/user]
public Fragment getItem(int position) {
WebViewFragment Fragment;
switch (position) {
case 0:
Fragment = new fragment1();
break;
case 1:
Fragment = new fragment2();
break;
case 2:
Fragment = new fragment3();
break;
case 3:
Fragment = new fragment4();
break;
case 4:
Fragment = new fragment5();
break;
default:
Fragment = null;
break;
}
lastFragment = Fragment;
return Fragment; [B]<-Error #2[/B]
}
[user=439709]@override[/user]
public int getCount() {
return 5;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.tab1).toUpperCase(l);
case 1:
return getString(R.string.tab2).toUpperCase(l);
case 2:
return getString(R.string.tab3).toUpperCase(l);
case 3:
return getString(R.string.tab4).toUpperCase(l);
case 4:
return getString(R.string.tab5).toUpperCase(l);
}
return null;
}
}
}
Error #1 is in line 26 and says:
Code:
The method tryGoBack() is undefined for the type WebViewFragment
Error #2 is in line 80 and says
Code:
Type mismatch: cannot convert from WebViewFragment to Fragment
Here is one of my fragment java files as well:
fragment1.java
Code:
package com.-----;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class fragment1 extends WebViewFragment {
public abstract class WebViewFragment extends Fragment{
public abstract void tryGoBack();
}
WebView myWebView;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment1, container, false);
myWebView = (WebView) root.findViewById(R.id.webview1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("url");
return root;
}
}
Any help is greatly appreciated!
When dealing with two or different classes which all extend one of them, so in this case the WebViewFragment extending Fragment and your fragment1 inheriting from WebViewFragment, you can convert the object simply putting
Code:
(NewType)
in front of it. So for error 1, insert (Fragment1) and for error 2 insert (Fragment).
One advice I'd like to give you, Capitalize class names and don't capitalize object and variable names, so it should be Fragment1 (maybe a more clear name) and WebViewFragment fragment.

(Q) Load Custom system font from Extend TextView class.

Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
SpaceCaker said:
Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
Click to expand...
Click to collapse
i have fixed it.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
Typeface tf = Typeface.createFromFile("/system/fonts/Cooljazz.ttf");
profilename.setTypeface(tf);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
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.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

Categories

Resources