I'm trying to make an Android application that access RottenTomatoes.com and loads the API data of upcoming movies.
I can successfully obtain the API data, but when I try to parse the data I run into trouble.
Here's the block of code that isn't working:
public class MovieJSONParser {
static public class MovieParser{
static ArrayList<Movie> parseMovie(String jsonString) throws JSONException {
ArrayList<Movie> movies = new ArrayList<Movie>();
JSONObject moviesJSON = new JSONObject(jsonString);
JSONArray moviesArray = moviesJSON.getJSONArray("movies");
Log.d("app", "in MovieJSONParser");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject o = moviesArray.getJSONObject(i);
Log.d("app", o.toString());
Log.d("app", "Created a JSON object to put in Movies");
// THIS LINE ISN'T WORKING
Movie movie = new Movie(o);
Log.d("app", "after Movie declaration");
movies.add(movie);
}
Log.d("app", "end of MovieJSONParser");
return movies;
}
}
}
I know the line of code that I labeled as not working isn't working because the log comments are all appearing correctly up until the statement:
Movie movie = new Movie(o);
This line of code is trivial... a simple class object declaration... I have no idea why it's making the program crash... There is no actual error. The program runs.
Here is my Movie.class:
public class Movie extends Activity {
String url_posterThumbnail, title, year, mpaa_rating;
int critics_score;
public Movie(JSONObject o) throws JSONException {
Log.d("app", "in Movie");
this.title = o.getString("title");
this.year = o.getString("year");
this.mpaa_rating = o.getString("mpaa_rating");
this.critics_score = o.getInt("critics_score");
this.url_posterThumbnail = o.getString("thumbnail");
}
public String returnUrl_posterThumbnail() {
return url_posterThumbnail;
}
public void setUrl_posterThumbnail(String url_posterThumbnail) {
this.url_posterThumbnail = url_posterThumbnail;
}
public String returnTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String returnYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String returnMpaa_rating() {
return mpaa_rating;
}
public void setMpaa_rating(String mpaa_rating) {
this.mpaa_rating = mpaa_rating;
}
public int returnCritics_score() {
return critics_score;
}
public void setCritics_score(int critics_score) {
this.critics_score = critics_score;
}
#Override
public String toString() {
return "Movie [url_posterThumbnail=" + url_posterThumbnail + ", title="
+ title + ", year=" + year + ", mpaa_rating=" + mpaa_rating
+ ", critics_score=" + critics_score + "]";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies, menu);
return true;
}
}
Here's my MainActivity.class in case you need it:
public class MainActivity extends Activity {
String APIKEY = "vs6hcrs57h4wy74u3zgxhmrm";
String url_MY_FAVORITE_MOVIES = "";
String url_BOX_OFFICE_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=3&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_IN_THEATRES_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=3&page=1&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_OPENING_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?limit=3&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_UPCOMING_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?page_limit=3&page=1&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
ListView listview;
ArrayList<Movie> movies = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("app", "Hi! In onCreate");
listview = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
listview.setAdapter(arrayAdapter);
arrayAdapter.add("My Favorite Movies");
arrayAdapter.add("Box Office Movies");
arrayAdapter.add("In Theatres Movies");
arrayAdapter.add("Opening Movies");
arrayAdapter.add("Upcoming Movies");
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int listViewPosition,
long arg3) {
Intent i = new Intent(getBaseContext(), MoviesDetails.class);
switch (listViewPosition) {
case 0:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_MY_FAVORITE_MOVIES).get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 1:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_BOX_OFFICE_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 2:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_IN_THEATRES_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 3:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_OPENING_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 4:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_UPCOMING_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
default:
break;
}
Log.d("app", "end of file?");
}
});
}
#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;
}
}
Lastly, here's my GetMoviesASYNCTASK.class if you need it:
public class GetMoviesASYNCTASK extends AsyncTask<String, Void, ArrayList<Movie>> {
String url_string;
ProgressDialog pd;
MainActivity main;
public GetMoviesASYNCTASK(MainActivity main){
this.main = main;
}
#Override
protected ArrayList<Movie> doInBackground(String... params) {
url_string = params[0];
// pd = new ProgressDialog(main);
// pd.setCancelable(false);
// pd.setMessage("Loading Movies...!");
// pd.show();
Log.d("app", "begin asynctask");
try {
URL url = new URL(url_string);//Parse the string as an url
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//create a http connection using that url
con.setRequestMethod("GET");//Use the get method
con.connect(); //Connect to http
int statusCode = con.getResponseCode();//Get the server's response
if (statusCode == HttpURLConnection.HTTP_OK) { //If server returns 200
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
Log.d("app", "String value of API stored");
ArrayList<Movie> movies = MovieJSONParser.MovieParser.parseMovie(sb.toString());
Log.d("app", "movies in ASYNCTASK initialized :)");
return movies;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("app", "asynctask didn't work");
return null;
}
// Override
protected void onPostExecute(ArrayList<Movie> result) {
//ArrayList<String> movieTitles = new ArrayList<String>();
super.onPostExecute(result);
Log.d("app", "exiting asynctask");
//pd.dismiss();
}
}
Am I missing something obvious?
Any help will be greatly appreciated!
critics_score is in ratings object but here you are trying to access that key directly. so it is throwing exception.
Better use optString() with some default value instead of getString(), as even if the key doesn't exist, will not end with exceptions..
Here is the working code :
JSONObject object = new JSONObject(result);
JSONArray records = object.getJSONArray("movies");
Log.d(LOG_TAG, "records" + records);
int len = records.length();
String albumart[] = new String[len];
for (int i = 0; i < len; i++) {
JSONObject record = (JSONObject) records.getJSONObject(i);
String extid = record.getString("id");
String accountName = record.optString("title", "No title");
JSONObject posters = record.getJSONObject("posters");
String albuart = posters.optString("detailed", null);
String critics = record.optString("critics_consensus", "No Critics");
String year = record.getString("year");
String rating = record.optString("mpaa_rating", "No rating");
JSONObject ratings = record.getJSONObject("ratings");
String rating = ratings.optString("critics_score", "");
if(rating.length() <= 0 ) {
rating = "0";
}
String audience_rating = ratings.optString("audience_rating", "");
if(audience_rating.length() <= 0 ) {
audience_rating = "0";
}
String duration = record.optString("runtime", "");
if(duration.length() <= 0 ) {
duration = "0"
}
}
Related
**here is my code in on create for questions on next button...**
public class QuizActivity extends AppCompatActivity {
private TextView quizQuestion;
private RadioGroup radioGroup;
private RadioButton optionOne;
private RadioButton optionTwo;
private RadioButton optionThree;
private RadioButton optionFour;
private int currentQuizQuestion;
private int quizCount;
private int score=0;
private int pagecount=1;
private QuizWrapper firstQuestion;
private List<QuizWrapper> parsedObject;
TextView pgcount;
ArrayList<String> arrayList;
int id=0;
**this is on oncareate function**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
quizQuestion = (TextView)findViewById(R.id.quiz_question);
arrayList=new ArrayList<String>();
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
optionOne = (RadioButton)findViewById(R.id.radio0);
optionTwo = (RadioButton)findViewById(R.id.radio1);
optionThree = (RadioButton)findViewById(R.id.radio2);
// optionFour = (RadioButton)findViewById(R.id.radio3);
final String rad= String.valueOf(radioGroup.getCheckedRadioButtonId());
pgcount = (TextView) findViewById(R.id.countpage);
// Button previousButton = (Button)findViewById(R.id.previousquiz);
Button nextButton = (Button)findViewById(R.id.nextquiz);
here i am calling the asynch class
AsyncJsonObject asyncObject = new AsyncJsonObject();
asyncObject.execute("");
**here is my next button for next question load..**
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int radioSelected = radioGroup.getCheckedRadioButtonId();
final int userSelection = getSelectedAnswer(radioSelected);
final int correctAnswerForQuestion = firstQuestion.getCorrectAnswer();
if(userSelection == correctAnswerForQuestion){
// correct answer
// Toast.makeText(QuizActivity.this, "You got the answer correct", Toast.LENGTH_LONG).show();
score++;
}
**here i am checking the whether it is button clicked or not**
if (radioGroup.getCheckedRadioButtonId()==-1) {
Toast.makeText(QuizActivity.this, "Please Select Answer", Toast.LENGTH_SHORT).show();
}else {
currentQuizQuestion++;
pagecount++;
}
**and here is my asynctask class for loading questions...**
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://learningcastles.com/chiesi/api/get_question");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " +
jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
here is preexecute function
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(QuizActivity.this, "Setting Up Quiz","Please Wait....", true);
}
**here is first time questions to be set**
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
pgcount.setText(String.valueOf(pagecount) + "/5");
}
here is string builder
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
**List of array to return object**
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("quiz_questions");
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray != null) {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("possible_answers");
int correctAnswer = jsonChildNode.getInt("correct_answer");
int is_delete = jsonChildNode.getInt("is_delete");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer,is_delete);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonObject;
}
**selecting the correct answer id**
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
// if(radioSelected == R.id.radio3){
// answerSelected = 4;
// }
return answerSelected;
}
unchecking the button for next question
private void uncheckedRadioButton(){
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
// optionFour.setChecked(false);
}
***problem is here in oncreate where i am calling on radiogroupcheckedchangelistner..where i am taking static id and set it when radio button is checked and comparing it with my correct answer for question..***
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radGroup, int i) {
***setting button to be disabled after one check***
optionOne.setEnabled(false);
optionTwo.setEnabled(false);
optionThree.setEnabled(false);
checking user selection
final int radioSelected = radioGroup.getCheckedRadioButtonId();
final int userSelection = getSelectedAnswer(radioSelected);
final int correctAnswerForQuestion =
getting correct answers
firstQuestion.getCorrectAnswer();
setting up ids when user check the button
if (optionOne.isChecked()){
id=1;
}
if (optionTwo.isChecked()){
id=2;
}
if (optionThree.isChecked()){
id=3;
}
// Toast.makeText(QuizActivity.this, ""+correctAnswerForQuestion+"="+""+id, Toast.LENGTH_LONG).show();
***here i am comparing the id that checked and correct answer of question then setting the color but for second question the id remain 1 why??***
if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.GREEN);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.GREEN);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion){
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.GREEN);
}
// else {
// optionOne.setTextColor(Color.RED);
// optionOne.setTextColor(Color.RED);
// optionOne.setTextColor(Color.RED);
// }
}
});
**but it is not setting the color for correct answer correctly what i am doing wrong any help would be appreciated..**
Just looked in your Code and I found this:
if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.GREEN);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.GREEN);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion){
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.GREEN);
}
All the conditions in the IF statements are the same!!
(id==correctAnswerForQuestion).
Change the Conditions to appropriate Logic because otherwise the other else if statements are useless.
Right now, I have an Activity that displays 10 listings from a JSON array. Next, on the swipe of an ImageView, I want to clear the ListView and display the next 10 (as a "next page" type thing). So, right now I do this
view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) {
#Override
public void onSwipeLeft() {
//clear adapter
adapter.clear();
//get listings 10-20
startLoop = 10;
endLoop = 20;
//call asynctask to display locations
FillLocations myFill = new FillLocations();
myFill.execute();
Toast.makeText(getApplicationContext(), "Left",
Toast.LENGTH_LONG).show();
}
and when I swipe it diisplays ONE item and I get this error
Error Parsing Data android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
What am I doing wrong? Thanks!
Full code:
public class MainActivity extends ActionBarActivity {
ListView listView;
int startLoop, endLoop;
TextView test;
ArrayList<Location> arrayOfLocations;
LocationAdapter adapter;
ImageView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLoop = 0;
endLoop = 10;
listView = (ListView) findViewById(R.id.listView1);
// Construct the data source
arrayOfLocations = new ArrayList<Location>();
// Create the adapter to convert the array to views
adapter = new LocationAdapter(this, arrayOfLocations);
FillLocations myFill = new FillLocations();
myFill.execute();
view = (ImageView) findViewById(R.id.imageView1);
view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) {
#Override
public void onSwipeLeft() {
adapter.clear();
startLoop = 10;
endLoop = 20;
FillLocations myFill = new FillLocations();
myFill.execute();
Toast.makeText(getApplicationContext(), "Left",
Toast.LENGTH_LONG).show();
}
});
}
private class FillLocations extends AsyncTask<Integer, Void, String> {
String msg = "Done";
protected void onPreExecute() {
progress.show();
}
// Decode image in background.
#Override
protected String doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://americanfarmstands.com/places/");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
// resultView.setText("connected");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = startLoop; i < endLoop; i++) {
//Toast.makeText(getApplicationContext(), i,
// Toast.LENGTH_LONG).show();
final JSONObject json = jArray.getJSONObject(i);
// counter++;
String initialURL = "http://afs.spotcontent.com/img/Places/Icons/";
final String updatedURL = initialURL + json.getInt("ID")
+ ".jpg";
Bitmap bitmap2 = null;
try {
bitmap2 = BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
return msg;
}
protected void onPostExecute(String msg) {
// Attach the adapter to a ListView
//ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
progress.dismiss();
}
}
Location Adapter:
public class LocationAdapter extends ArrayAdapter<Location> {
public LocationAdapter(Context context, ArrayList<Location> locations) {
super(context, R.layout.item_location, locations);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Location location = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails);
TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance);
TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours);
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
// Populate the data into the template view using the data object
tvName.setText(location.name);
tvDetails.setText(location.details);
tvDistance.setText(location.distance);
tvHours.setText(location.hours);
ivIcon.setImageBitmap(location.icon);
// Return the completed view to render on screen
return convertView;
}
}
EDIT: Updated Code:
for (int i = startLoop; i < endLoop; i++) {
// Toast.makeText(getApplicationContext(), i,
// Toast.LENGTH_LONG).show();
final JSONObject json = jArray.getJSONObject(i);
// counter++;
String initialURL = "http://afs.spotcontent.com/img/Places/Icons/";
final String updatedURL = initialURL + json.getInt("ID")
+ ".jpg";
final Bitmap bitmap2 =BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
//try {
// bitmap2 = BitmapFactory
// .decodeStream((InputStream) new URL(updatedURL)
// .getContent());
//} catch (MalformedURLException e) {
// e.printStackTrace();
//} catch (IOException e) {
// e.printStackTrace();
//}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The adapter must be updated from the UI thread.
You should change your AsyncTask into AsyncTask<Integer, Void, List<Location>>, and have the loop in on doInBackground() create a collection of Location and return it (instead of directly changing the adapter).
Finally, in onPostExecute(List<Location> result), do:
adapter.clear();
for (Location location : result)
adapter.add(location);
The error is clearly saying that you are trying to update View from a different thread(doInBackground) that catch an exception CalledFromWrongThreadException.
This line is the cause of the problem
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
that it should be called in the Main thread.
solution:
Call the main thread and update the adapter from there
example:
try {
final Bitmap bitmap2 = BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Move this bunch of code to onPostExecute
protected void onPostExecute(String msg) {
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Attach the adapter to a ListView
//ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
progress.dismiss();
}
Make Bitmap a class variable.
I am a beginner in Android programming. I'm trying to put an ID identifier coming from MySQL database using JSON to my listview items but I can't make it work. When i click on an item it should probably give the id of the item I clicked but it is not working and all I can get is a false.
public class MessagingListFragment extends Fragment {
private String jsonResult;
private String url = "http://10.0.2.2/mobile/get_my_ins.php";
private ListView listView;
List<NameValuePair> nameValuePairs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.messaging_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
accessWebService();
return rootView;
}
// Async Task to access the web
#SuppressLint("NewApi")
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("stud_id",MainActivity.user_id));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
}
}// end async task
public void accessWebService() {
try{
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 3", Toast.LENGTH_LONG).show();
}
}
// build hash set for list view
public void ListDrawer() {
List<Map<String, String>> classList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("recipient");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String friend = jsonChildNode.optString("last_name") + ", " + jsonChildNode.optString("first_name");
String outPut = friend;
classList.add(createMsgList("recipient", outPut));
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.getMessage().toString() + " 1", Toast.LENGTH_LONG).show();
}
try{
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity() , classList,
android.R.layout.simple_list_item_1, new String[] { "recipient" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int i,
long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 2", Toast.LENGTH_LONG).show();
}
}
private HashMap<String, String> createMsgList(String name, String subject) {
HashMap<String, String> friendList = new HashMap<String, String>();
friendList.put(name, subject);
return friendList;
}
}
You are popping up a Toast with listView.getId() as the textual content. This will always give you the ID of the listview that is containing your list items.
If you want to grab the data for the view, you will either need to use the position parameter (int i in the onItemClick method), or you can try to grab the data from the View v if it is a custom view.
For example, instead of passing in a String array into your adapter, you can keep a reference to the array and find the data you are looking for with myArray[i].
by calling listView.getId() you requested the listview id not the item inside listview
change
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
to
Toast.makeText(getActivity(), "my id and position = "+i, Toast.LENGTH_LONG).show();
i is the item position inside listview and JSONArray
hope this information helpful to you
Posts.java
public class Posts extends Activity implements OnCheckedChangeListener {
private static final String TAG = "POSTS";
private static final int NULL_COUNTRY_CODE = 6;
private static final int POST_BACK_BTN = 7;
private static final int CHANGE = 8;
private String un;
private SimpleAdapter simpleAdpt;
private EditText post;
private RadioGroup radGrp;
private GPSTracker mGPS;
private PullToRefreshListView lv;
private String initial = "Se eida ";
private String code;
private String unm;
private String postui;
private String tmp;
private String idPost;
// The data to show
private List<Map<String, String>> postsList = new ArrayList<Map<String, String>>();
JSONArray array = null;
private static List<String> list = new ArrayList<String>();
private String pst;
private AlertDialogFragments adf;
private FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
initLocation();
if (code == null) {
ft = getFragmentManager().beginTransaction();
// Create and show the dialog.
adf = new AlertDialogFragments(NULL_COUNTRY_CODE);
adf.show(ft, "dialog");
}
init();
}
private HashMap<String, String> createPost(String key, String name) {
HashMap<String, String> post = new HashMap<String, String>();
post.put(key, name);
return post;
}
private void initLocation() {
mGPS = new GPSTracker(this);
final double mLat = mGPS.getLatitude();
final double mLong = mGPS.getLongitude();
getAddress(mLat, mLong);
}
private void getAddress(double mLat, double mLong) {
try {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(mLat, mLong, 100);
if (addresses.size() > 0) {
addresses = gcd.getFromLocation(mLat, mLong, 1);
code = addresses.get(0).getCountryCode();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void init() {
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Intent i = getIntent();
un = i.getStringExtra("un");
post = (EditText) findViewById(R.id.lbl_txt);
radGrp = (RadioGroup) findViewById(R.id.rdg);
radGrp.setOnCheckedChangeListener(this);
// We get the ListView component from the layout
lv = (PullToRefreshListView) findViewById(R.id.listView);
// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) lv)
.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
((PullToRefreshListView) lv)
.setLastUpdated(new SimpleDateFormat(
"dd-MM-yyyy HH:mm").format(new Date()));
new GetData().execute();
}
});
simpleAdpt = new CustomAdapter(this, postsList,
android.R.layout.simple_list_item_1, new String[] { "post" },
new int[] { android.R.id.text1 });
new GetData().execute();
}
public class CustomAdapter extends SimpleAdapter {
HashMap<String, String> map = new HashMap<String, String>();
public CustomAdapter(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row != null) {
if (position % 2 == 0)
row.setBackgroundResource(R.drawable.listview_selector_even);
else
row.setBackgroundResource(R.drawable.listview_selector_odd);
}
return row;
}
}
private class GetData extends AsyncTask<String, String, String> {
private ProgressDialog progDailog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(Posts.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected String doInBackground(String... params) {
postsList.clear();
list.clear();
new Thread(new Runnable() {
public void run() {
//getting data from server and store into results
try {
array = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < array.length(); i++) {
JSONObject row = null;
try {
row = array.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
unm = row.getString("Username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
postui = row.getString("Post");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = row.getString("Timestamp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
idPost = row.getString("Id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pst = unm + ":\n" + postui + "\n"
+ tmp.substring(0, tmp.length() - 2);
list.add(i, idPost);
postsList.add(createPost("post", pst));
}
runOnUiThread(new Runnable() {
#Override
public void run() {
lv.setSelector(R.drawable.row_pressed);
lv.setAdapter(simpleAdpt);
simpleAdpt.notifyDataSetChanged();
registerForContextMenu(lv);
}
});
}
}).start();
return null;
}
#Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
simpleAdpt.notifyDataSetChanged();
progDailog.dismiss();
((PullToRefreshListView) lv).onRefreshComplete();
}
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap<?, ?> map = (HashMap<?, ?>) simpleAdpt
.getItem(aInfo.position - 1);
String string = (String) map.get("post");
menu.setHeaderTitle("Options");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
menu.add(1, 3, 3, "Delete");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
}
// This method is called when user selects an Item in the Context menu
#SuppressWarnings("deprecation")
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (itemId) {
case 1:
// Share intent
String key = ((TextView) info.targetView).getText().toString();
// create the send intent
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
// set the type
shareIntent.setType("text/plain");
// add a subject
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
R.string.app_name);
// build the body of the message to be shared
String shareMessage = key.substring(0, key.length() - 20)
.substring(key.indexOf(":") + 2);
// add the message
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
shareMessage);
// start the chooser for sharing
startActivity(Intent.createChooser(shareIntent, "Share via: "));
break;
case 2:
// Copy
String key1 = ((TextView) info.targetView).getText().toString();
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("", key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
clipboard.setPrimaryClip(clip);
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
}
break;
case 3:
// Delete
int index = info.position - 1;
//deletes a post
deletePost(list.get(index), this);
new GetData().execute();
break;
}
return true;
}
My Logcat output
The content of the adapter has changed but ListView did not receive a
notification. Make sure the content of your adapter is not modified
from a background thread, but only from the UI thread.
You are using postList as content for your adapter. Then you change that content in doInBackground(). You cannot do that.
Here's what you have to do. Gather the data in doInBackground() and return it. The result will be passed to onPostExecute. Then, in onPostExecute, change the adapter content and notify about the data change. onPostExecute() runs in the UI thread.
If you want to periodically update your AdapterView, use publishProgress.
You don't need to start a new Thread in doInBackground and you don't need to invoke any runOnUIThread method. It will work (especially the runOnUIThread part) but then you don't need the AsyncTask class.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm setting a breakpoint at:
public ContentValues getValues() {
however the code never appears to reach it and I'm not sure why.
(any input is greatly appreciated)
SOURCE:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button assist_update_btn = null;
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
private Button mAssistUpdateButton = null;
private ImageView mLoadingCircle;
private int mInstructionNumber = 0;
public ArrayList<String> ValueArr = new ArrayList<String>();
public ArrayList<String> nameArr = new ArrayList<String>();
public ArrayList<String> ApnArr = new ArrayList<String>();
public ArrayList<String> mmscArr = new ArrayList<String>();
public ArrayList<String> mmsportArr = new ArrayList<String>();
public ArrayList<String> mmsproxyArr = new ArrayList<String>();
public ArrayList<String> portArr = new ArrayList<String>();
public ArrayList<String> proxyArr = new ArrayList<String>();
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
public static int TotalSteps = 8;
public static int count;
int i, g = 0;
Context ctx;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static BigInteger id1, id2;
BigInteger[] id;
public static Integer mdn1, mdn2;
public static String car;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static String Base_URL = "https://www.mysettings.com/";
NetworkTask task = new NetworkTask();
NetworkTask tasks = new NetworkTask();
InputStream stream = null;
private AnimationDrawable loadingAnimation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
task = new NetworkTask();
handler = new XmlParserHandlerFinal();
handler.setContext(ctx);
getImpVariablesForQuery();
if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
// updating layout initially has updating text with 1 dot in the
// This image view has the updating text to be progressively
// updated
// with dots addition
ImageView loading = (ImageView) findViewById(R.id.loading_empty1);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating1);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading2 = (ImageView) findViewById(R.id.loading_empty2);
// Set updating button to drawable animation
loading2.setBackgroundResource(R.drawable.updating2);
loadingAnimation = (AnimationDrawable) loading2.getBackground();
ImageView loading3 = (ImageView) findViewById(R.id.loading_empty3);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating3);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading4 = (ImageView) findViewById(R.id.loading_empty4);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating4);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading5 = (ImageView) findViewById(R.id.loading_empty5);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating5);
loadingAnimation = (AnimationDrawable) loading.getBackground();
tasks.execute("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
if (tasks.get() != null) {
stream = tasks.getInputStream();
Log.v("CfA", "here");
} else if (tasks.get() == null) {
setContentView(R.layout.error);
}
handler.getQueryResponse(stream);
Values = getContentValues();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Update APN table in separate thread
new TableUpdateRequestTask().execute("");
} else {// ICS and later versions
// startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
handler.getQueryResponse(stream);
Values = getContentValues();
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new TableUpdateRequestTask().execute("");
}
}
private ContentValues getContentValues() {
ContentValues values = new ContentValues();
System.out.println("count" + count);
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
private void getImpVariablesForQuery() {
// to get MDN
Integer MDN = Integer.parseInt(tm.getSimOperator());
Log.d("MDN", MDN.toString());
mdn1 = MDN % 1234;
Log.d("mdn1", mdn1.toString());
mdn2 = MDN / 1234;
Log.d("mdn2", mdn2.toString());
// to retrieve ICCID number of the SIM
String ICCID = tm.getSimSerialNumber();
Log.d("ICCID", ICCID);
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
id1 = id[1];
System.out.println("ICCID%1234 = " + id1);
id2 = id[0];
System.out.println("ICCID/1234 = " + id2);
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
car = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
car = "ATT";
}
}
#SuppressWarnings("unused")
public ContentValues generateTFConfig() throws IOException, SAXException,
ParserConfigurationException {
String operator = tm.getSimOperator();
ContentValues values = new ContentValues();
// Query the carrier table for the current data settings
Cursor c = getContentResolver().query(APN_TABLE_URI, null, "current=?",
new String[] { "1" }, null);
values = copyRecordFields(c);
String charset = "UTF-8";
String Append_URL = "settingsquery?";
String param1 = "mdn1=";
String param2 = "&mdn2=";
String param3 = "&car=";
String param4 = "&id1=";
String param5 = "&id2=";
String URL = "";
String parameters = param1 + mdn1 + param2 + mdn2 + param3 + car
+ param4 + id1 + param5 + id2;
URL = Base_URL + Append_URL + parameters;
Log.i("url...", URL);
new NetworkTask().execute(URL);
return values;
}
public int InsertAPN() throws SecurityException {
int id = -1;
if (i < nameArr.size()) {
for (i = 0; i < nameArr.size(); i++) {
ContentValues values2 = new ContentValues();
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
}
return id;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
/*
* Copy all data associated with the 1st record Cursor c. Return a
* ContentValues that contains all record data.
*/
private ContentValues copyRecordFields(Cursor c) {
if (c == null)
return null;
int row_cnt = c.getCount();
Log.d(TAG, "Total # of records: " + row_cnt);
ContentValues values = new ContentValues();//
if (c.moveToFirst()) {
String[] columnNames = c.getColumnNames();
Log.d(TAG, getAllColumnNames(columnNames));
String row = "";
for (String columnIndex : columnNames) {
int i = c.getColumnIndex(columnIndex);
row += c.getString(i) + ":\t";
// id to be auto-generated upon record insertion
values.put(columnIndex, c.getString(i));
}
row += "\n";
Log.d(TAG, row);
Log.d(TAG, "End Of Records");
}
return values;
}
// showAlert displays the text contained in message as an alert
public void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ConfigFinalActivity.this.finish();
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showErrorAlert displays an alert with layout and a title
private void showErrorAlert(int layoutRes, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setTitle(title)
.setView(inflater.inflate(layoutRes, null))
.setPositiveButton(getString(R.string.assisted_button),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(
Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showNotification starts the process of sending notifications to the bar
// to assist the user in updating the data settings on ICS and later
// versions of Android
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void showNotification() throws SAXException, ParserConfigurationException {
String field = getString(R.string.config_name_label);
// Log.d(Values);
String value = Values.get("name").toString();
System.out.println("DEBUG THIS");
System.out.println(Values);
int mId = 1;
String title = "1 of " + UpdateActivity.TotalSteps + " (Update "
+ field + ":)";
Notification.Builder mBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
.setContentText(value);
Intent resultIntent = new Intent(this,
NotificationActivityForMultiProf.class);
resultIntent.putExtra(field, value);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotification = mBuilder.getNotification();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(mId, mNotification);
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
if (mNotification != null) {
outState.putString("NOTIFICATIONB", mNotification.toString());
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void onClick(View v) {
if (v == assist_update_btn) {
// /// add instructions here
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
// This thread performs the setting update and shows pseudo progress update
public class TableUpdateRequestTask extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//
}
#Override
protected String doInBackground(String... params) {
int result = 0;
{
// The code below plays a ST Promo animation
// prior to displaying update success or failure message
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping
// and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
if (result != -1)
return "success";
else
return "failure";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Show updated screen if table was successfully updated
// Or alert indicating settings are not updated
if (result.equals("success")) {
assistUpdate();
} else
setContentView(R.layout.error);
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}
private int updateTable() throws IOException, SAXException,
ParserConfigurationException {
int insertResult = -1;// returned value if table is not properly updated
try {
ContentValues TFCarrierTableEntry = generateTFConfig();
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo))) {
// delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_tmo) });
// Insert NET10 Data Settings into Carrier table
insertResult = InsertAPN();
} else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_att) });
// Insert NET10 Data Settings into Carrier table
insertResult = InsertAPN();
} else
// non SM/ non T-Mo SIM
showAlert(getString(R.string.insert_sm_dialog));
} catch (SecurityException e) {
showErrorAlert(R.layout.assisted_setting,
getString(R.string.assited_title));
Log.d(TAG, e.getMessage());
}
return insertResult;
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener(this);
}
// This function return a cursor to the table holding the
// the APN configurations (Carrier table)
public Cursor getConfigTableCursor() {
return getContentResolver()
.query(APN_TABLE_URI, null, null, null, null);
}
public ArrayList<String> getnameArr() {
System.out.println("test");
System.out.println(nameArr);
nameArr.add("testing123");
return nameArr;
}
public ArrayList<String> getApnArr() {
System.out.println(ApnArr);
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
System.out.println(mmscArr);
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
System.out.println(mmsproxyArr);
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
System.out.println(mmsportArr);
return mmsportArr;
}
public int getCount() {
System.out.println(count);
return count;
}
public ArrayList<String> getProxyArr() {
System.out.println(proxyArr);
return proxyArr;
}
public ArrayList<String> getPortArr() {
System.out.println(portArr);
return portArr;
}
private void setProgressImgView(Integer imgViewId1, Integer imgViewId2,
Integer imgViewId3, Integer imgViewId4, Integer imgViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setImageResource(imgViewId1);
mProgressImageview2.setImageResource(imgViewId2);
mProgressImageview3.setImageResource(imgViewId3);
mProgressImageview4.setImageResource(imgViewId4);
mProgressImageview5.setImageResource(imgViewId5);
// mLoadingCircle = (ImageView) findViewById(R.id.loading_empty);
}
class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private InputStream stream;
#Override
protected InputStream doInBackground(String... params) {
Bundle queryResults = null;
String urlQueryString = params[0];
try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/33333333/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
Bundle queryResults = new Bundle();
HttpsURLConnection https = null;
String uri = urlQueryString;
// URL urlo = new URL(urlQueryString);
URL urlo = new URL(uri);
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();
// xmlStream = new BufferedInputStream(https.getInputStream());
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
// String queryResult = handler.getQueryResponse(stream );
String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);
return stream;
}
public InputStream getInputStream() {
return stream;
}
#Override
protected void onPostExecute(InputStream stream) {
}
}
}
It is not called.
The call to it is at
public int InsertAPN() throws SecurityException {
int id = -1;
if (i < nameArr.size()) {
for (i = 0; i < nameArr.size(); i++) {
ContentValues values2 = new ContentValues();
values2 = getValues();
That call is in a loop over each element of nameArr, which initialized with zero elements:
public ArrayList<String> nameArr = new ArrayList<String>();
Hence the loop will run zero times. The only function that adds elements to the List is the getnameArr() function, which is never called.